如何读取特定文件夹内的所有文件

我想读取c#.net中特定文件夹内的所有xml文件

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

我有多个产品在类别文件夹..要循环的文件夹,并应获得所有产品的XML文件名。

 XDocument doc2 = XDocument.Load((PG.SMNR.XMLDataSourceUtil.GetXMLFilePath(Locale, "Products/category/x1.xml"))); 
 using System.IO; ... foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml")) { string contents = File.ReadAllText(file); } 

注意上面使用.NET 4.0function; 在以前的版本中用GetFilesreplaceEnumerateFiles )。 另外,将File.ReadAllTextreplace为读取xml文件的首选方式 – 也许是XDocumentXmlDocumentXmlReader

 using System.IO; DirectoryInfo di = new DirectoryInfo(folder); FileInfo[] files = di.GetFiles("*.xml"); 
 using System.IO; //... string[] files; if (Directory.Exists(Path)) { files = Directory.GetFiles(Path, @"*.xml", SearchOption.TopDirectoryOnly); //... 

您可以使用DirectoryInfo.GetFiles方法:

 FileInfo[] files = DirectoryInfo.GetFiles("*.xml"); 

如果您要复制一个文件夹中的所有文本文件以合并并复制到另一个文件夹,可以这样做:

 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()); } } } } 
  using System.IO; string[] arr=Directory.GetFiles("folderpath","*.Fileextension"); foreach(string file in arr) { }