Search code examples
c#xmlfile

how to read all files inside particular folder


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")));

Solution

  • 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.