2011-04-30 91 views
67

我想讀在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"))); 
+4

你嘗試過什麼?什麼沒有用?你在哪裏遇到困難? http://tinyurl.com/so-hints – Oded 2011-04-30 07:56:16

回答

170
using System.IO; 
... 
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml")) 
{ 
    string contents = File.ReadAllText(file); 
} 

注意上述使用.NET 4.0特徵;在以前的版本中用GetFiles代替EnumerateFiles)。另外,用您喜歡的讀取xml文件的方式替換File.ReadAllText - 可能是XDocument,XmlDocumentXmlReader

+1

'System.IO.Directory'不包含'EnumerateFiles' – ram 2011-04-30 08:11:50

+6

@ram的定義 - 我在我的答案中解釋了這一點;請閱讀示例下的文本... – 2011-04-30 08:19:39

+1

謝謝Marc其作品.. :-) – ram 2011-04-30 08:25:51

12
using System.IO; 

//... 

    string[] files; 

    if (Directory.Exists(Path)) { 
    files = Directory.GetFiles(Path, @"*.xml", SearchOption.TopDirectoryOnly); 
    //... 
16
using System.IO; 

DirectoryInfo di = new DirectoryInfo(folder); 
FileInfo[] files = di.GetFiles("*.xml"); 
4

如果你正在尋找所有文本文件複製一個文件夾中進行合併,並複製到另一個文件夾,你可以做到這一點,以實現這一目標:

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

     } 
+0

儘管這個解決方案可能會回答OP的問題,建議不要只寫一個代碼專用的答案,因爲這對未來的用戶可能不是很有幫助。詳細說明一下。這個解決方案提供了什麼?它將如何使OP受益?等等。 – 2017-05-11 11:46:20

+0

我只是看過昨天的代碼,但那不是複製粘貼 – 2017-05-11 11:48:37

+0

我並不是暗示你要複製/粘貼,我已經更新了我的評論,儘管如此,我的評論仍然存在,詳細說明。 – 2017-05-11 11:50:10