how to read all files inside particular folder

ram picture ram · Apr 30, 2011 · Viewed 245.1k times · Source

I want to read all xml files inside a particular folder in c# .net

XDocument doc2 = XDocument.Load((PG.SMNR.XMLDataSourceUtil.GetXMLFilePath(Locale, "Products/category/product.xml")));

i have multiple products in category folder.. want loop the folder and should get all product xml file names.

XDocument doc2 = XDocument.Load((PG.SMNR.XMLDataSourceUtil.GetXMLFilePath(Locale, "Products/category/x1.xml")));

Answer

Marc Gravell picture Marc Gravell · Apr 30, 2011
using System.IO;
...
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
    string contents = File.ReadAllText(file);
}

Note the above uses a .NET 4.0 feature; in previous versions replace EnumerateFiles with GetFiles). Also, replace File.ReadAllText with your preferred way of reading xml files - perhaps XDocument, XmlDocument or an XmlReader.