Reputation: 1528
I need to walk a folder tree in C# and somehow record what I find, then pass it as a string to another device on my network, where I will display it graphically.
Walking the folder tree is simple with recursion, as is passing the string along.
However I would like the format of the string to be as portable as possible, so I thought of XML. I'm guessing I can somehow serialise the XML to a string.
I'm very new to XML, so I'm unsure how best to proceed. I'm thinking the format should end up something like this example:
<Tree>
<Folder Name="Folder1">
<File Name="File1" />
</Folder>
</Tree>
Any ideas? Do I use LinqToXML to build the string out of XElement objects like an example I've seen, or is that not the best way?
Upvotes: 4
Views: 620
Reputation: 1528
Ok so I went ahead with XElement - turns out it's as easy as Chuck Savage said :)
private void BuildFolderTree(DirectoryInfo parentFolder, XElement parentElement)
{
// Find all the subfolders under this folder.
foreach (DirectoryInfo folderInfo in parentFolder.GetDirectories())
{
// Add this folder to the doc.
XElement folderElement = new XElement("Folder", new XAttribute("Name", folderInfo.Name), new XAttribute("Path", folderInfo.FullName));
parentElement.Add(folderElement);
// Recurse into this folder.
BuildFolderTree(folderInfo, folderElement);
}
// Process all the files in this folder
foreach (FileInfo fileInfo in parentFolder.GetFiles("*.*"))
{
// Add this file minus its extension.
parentElement.Add(new XElement(STR_File, new XAttribute("Name", fileInfo.Name), new XAttribute("Path", fileInfo.FullName)));
}
}
// main code
DriveInfo di = new DriveInfo("M");
XElement usbKeyTreeElement = new XElement("USBKey");
BuildFolderTree(di.RootDirectory, usbKeyTreeElement);
string usbKeyString = usbKeyTreeElement.ToString();
usbKeyString ends up looking something like this:
<USBKey>
<Folder Name="folder1" Path="M:\folder1" />
<Folder Name="folder2" Path="M:\folder2">
<File Name="file1" Path="M:\folder2\file1.txt" />
<File Name="file2" Path="M:\folder2\file2.txt" />
</Folder>
</USBKey>
Upvotes: 2
Reputation: 24723
It's parsing at the end of the day; any format with a given delimiter should suffice.
Folder/Folder/Folder/Folder/Blah.txt
The above should be much more succinct than the overhead of XML and also meet your portability needs.
Upvotes: 2