Loop through main folder and subfolders



I only manage to produce the below code for looping through all the XML files in a folder and write into a csv file.



XmlDocument xmlDoc = new XmlDocument();
string[] fileEntries = Directory.GetFiles(@"..\..\bin\Debug\commentsXML\");
foreach (string fileName in fileEntries)
{
try
{
string docPath = fileName;
//load the XML document from the specified file
xmlDoc.Load(docPath);
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("item");
using (FileStream fs = new FileStream(@"..\..\bin\Debug\" + "Comments.csv", FileMode.Append))
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (XmlNode node in nodeList)
{
//do the writing
}
sw.Flush();
sw.Close();
fs.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("Done writing into comments.csv!");


The above code is for the folder/file structure of:



|--Main Folder


|---XML1


|---XML2


|---XML3



What if I have a new folder/file structure like below? Could anyone be kind enough to point me out how to write/modify the foreach loop?


Main Folder



  • Subfolder1

    • XML1

    • XML2

    • XML3



  • Subfolder2

    • XML1

    • XML2

    • XML3



  • Subfolder3

    • XML1

    • XML2

    • XML3




No comments:

Post a Comment