2015-05-11 34 views
1

我需要閱讀一個文件夾,其中包含多個內部文件夾,其中有超過100個xml文件。我需要逐個讀取所有這些xml文件。我正在使用asp.net c#。我怎樣才能做到這一點。在asp.net中計算總文件夾

例如:A是我的文件夾,包含123456 ... 200的子文件夾。 現在該文件夾1包含a.xmlb.xmlc.xml ...同樣的文件夾2包含1.xml2.xml3.xml ... 現在我需要閱讀所有這些XML文件一個接一個地從每個文件夾。

+0

是你的工作??? –

+0

有多少個文件夾級別。如果它的無限制,你需要使用遞歸 – Wize

回答

0

,您可以利用並行LINQ的和做如下

int count = 0; 
    string[] files = null; 
    try 
    { 
     files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories); 
    } 
    catch (UnauthorizedAccessException e) 
    { 
     Console.WriteLine("You do not have permission to access one or more folders in this directory tree."); 
     return; 
    } 

    catch (FileNotFoundException) 
    { 
     Console.WriteLine("The specified directory {0} was not found.", path); 
    } 

    var fileContents = from file in files.AsParallel() 
      let extension = Path.GetExtension(file) 
      where extension == ".xml" 
      let text = File.ReadAllText(file) 
      select new FileResult { Text = text , FileName = file }; //Or ReadAllBytes, ReadAllLines, etc.    

    try 
    { 
     foreach (var item in fileContents) 
     { 
      Console.WriteLine(Path.GetFileName(item.FileName) + ":" + item.Text.Length); 
      count++; 
     } 
    } 
    catch (AggregateException ae) 
    { 
     ae.Handle((ex) => 
      { 
       if (ex is UnauthorizedAccessException) 
       { 
        Console.WriteLine(ex.Message); 
        return true; 
       } 
       return false; 
      }); 
    } 

例takem:https://msdn.microsoft.com/en-us/library/ff462679%28v=vs.110%29.aspx

+0

Thank's Pranay,它爲我工作。 – user3810961

+1

@ user3810961 - 將答案標記爲已接受,如果它對您有效,請投票 –