How to read all files inside a specific folder

I want to read all xml files inside a specific folder in C # .net

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

I have several products in a category folder. want to encode the folder and get all the xml file names.

 XDocument doc2 = XDocument.Load((PG.SMNR.XMLDataSourceUtil.GetXMLFilePath(Locale, "Products/category/x1.xml"))); 
+67
c # xml file
Apr 30 2018-11-11T00:
source share
6 answers
 using System.IO; ... foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml")) { string contents = File.ReadAllText(file); } 

Note that the above example uses the .NET 4.0 function; in previous versions, replace EnumerateFiles with GetFiles ). Also, replace File.ReadAllText with your preferred way to read xml files - perhaps XDocument , XmlDocument or XmlReader .

+170
Apr 30 2018-11-11T00:
source share
 using System.IO; DirectoryInfo di = new DirectoryInfo(folder); FileInfo[] files = di.GetFiles("*.xml"); 
+16
Apr 30 2018-11-11T00:
source share
 using System.IO; //... string[] files; if (Directory.Exists(Path)) { files = Directory.GetFiles(Path, @"*.xml", SearchOption.TopDirectoryOnly); //... 
+12
Apr 30 '11 at 8:00
source share

You can use the DirectoryInfo.GetFiles method:

 FileInfo[] files = DirectoryInfo.GetFiles("*.xml"); 
+4
Apr 30 2018-11-11T00:
source share

If you want to copy all text files into one folder for merging and copying to another folder, you can do this to achieve this:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace HowToCopyTextFiles { class Program { static void Main(string[] args) { string mydocpath=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); StringBuilder sb = new StringBuilder(); foreach (string txtName in Directory.GetFiles(@"D:\Links","*.txt")) { using (StreamReader sr = new StreamReader(txtName)) { sb.AppendLine(txtName.ToString()); sb.AppendLine("= = = = = ="); sb.Append(sr.ReadToEnd()); sb.AppendLine(); sb.AppendLine(); } } using (StreamWriter outfile=new StreamWriter(mydocpath + @"\AllTxtFiles.txt")) { outfile.Write(sb.ToString()); } } } } 
+4
Mar 15 2018-12-12T00:
source share
  using System.IO; string[] arr=Directory.GetFiles("folderpath","*.Fileextension"); foreach(string file in arr) { } 
-one
May 11 '17 at 11:38 a.m.
source share



All Articles