Search This Blog

Generate XML from directory Structure

The given code snippets is used to generate the Directory Structure to an XML File.

This XML File can be used in various ways, for appending in treeview, store as a file, export in string format etc.

public String getXMLFromDirectoryStructure()




string ProjectFolder = "Project"; //absolute path for project

string appPath = "C:\Project"; //absolute path for project

string bodyFile = Path.Combine(appPath, @"Snippets\");

XmlDocument doc = new XmlDocument();

doc.LoadXml("< $ProjectFolder$ name=\"$ProjectFolder$\" type=\"DIR\">" + "</$ProjectFolder$>");

DirectoryInfo mainDir = new DirectoryInfo(bodyFile);

foreach (DirectoryInfo dir in mainDir.GetDirectories())


XmlElement elem = GetData(dir.FullName, doc);



StringWriter sw = new StringWriter();

XmlTextWriter tx = new XmlTextWriter(sw);


doc.Save(bodyFile + "\\" + "Path.xml");

return sw.ToString();


catch (Exception)



return "";


private static XmlElement GetData(string dirName, XmlDocument doc)


//create a new node for this directory

XmlElement elem = doc.CreateElement("dir");

DirectoryInfo di = new DirectoryInfo(dirName);

elem.SetAttribute("name", di.Name);

elem.SetAttribute("type", "DIR");

foreach (DirectoryInfo dinf in di.GetDirectories())


//Recursively call the directory with all underlying dirs and files

XmlElement elemDir = GetData(dirName + "\\" + dinf.Name, doc);

if (dinf.GetDirectories().Count() + dinf.GetFiles().Count() == 0)


elemDir.InnerText = "";




return elem;


Submitted By Nipesh Shah @ 9/19/2011 4:56:27 PM

Link Within Related Posts Plugin for WordPress, Blogger...
There was an error in this gadget