2017-01-12 46 views
-1

我正在寫一個程序,其中有一個文件夾數量非常大的文件(超過數千)。我想要一個有效的方式來「打開每個文件並對其進行處理。處理包括調用數據庫取決於file.I的內容存儲過程寫了下面的代碼讀取每個file.Please的內容讓我知道如果任何改進或替代方案。處理大量的文件c#

using System; 
using System.Collections.Generic; 
using System.Diagnostics; 
using System.IO; 
using System.Security; 
using System.Threading; 
using System.Threading.Tasks; 
using System.Text; 
using System.Collections; 

class Program 
{ 
    static void Main() 
    { 
     ProcessRead().Wait(); 
     Console.Write("Done "); 
     Console.ReadKey(); 
    } 

    static async Task ProcessRead() 
    { 
     var sw = Stopwatch.StartNew(); 
     string folder = @"Directory"; 

     string[] fileEntries = Directory.GetFiles(folder); 
     int count = 0; 

     foreach (string fname in fileEntries) 
     { 
      if (File.Exists(fname) == false) 
      { 
       Console.WriteLine("file not found: " + fname); 
      } 
      else 
      { 
       try 
       { 
        count++; 
        string text = await ReadTextAsync(fname); 
        Console.WriteLine(text); 
       } 
       catch (Exception ex) 
       { 
        Console.WriteLine(ex.Message); 
       } 
      } 
     } 
     Console.WriteLine("Elapsed Time" + sw.ElapsedMilliseconds); 
     Console.WriteLine(count); 
    } 

    static async Task<string> ReadTextAsync(string filePath) 
    { 
     using (FileStream sourceStream = new FileStream(filePath, 
      FileMode.Open, FileAccess.Read, FileShare.Read, 
      bufferSize: 4096, useAsync: true)) 
     { 
      StringBuilder sb = new StringBuilder(); 

      byte[] buffer = new byte[0x1000]; 
      int numRead; 
      while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0) 
      { 
       string text = Encoding.UTF8.GetString(buffer, 0, numRead); 
       sb.Append(text); 
      } 

      return sb.ToString(); 
     } 
    } 
} 
+7

因爲這是工作的代碼,你可以在[代碼審查]有更好的運氣比(http://codereview.stackexchange.com) - 但是,請花有一點時間要正確地格式化你的代碼併發布之前。 – Rob

+2

是的,Code Review是一個更好的地方。確保包含調用存儲過程的代碼,否則它們將無法提供答案(問題可能會被關閉)。 – Alexei

+3

我投票結束了這個題目,因爲它屬於Code Review stackexchange。 –

回答

0

這可能取決於許多參數,如作爲文件大小...但您可以嘗試避免StringBuilder追加以下代碼並檢查它是否具有更好的性能:

byte[] data; 
int n; 

using (FileStream sourceStream = File.Open(filename, FileMode.Open)) 
{ 
    n = (int)sourceStream.Length; 
    data = new byte[n]; 
    await sourceStream.ReadAsync(result, 0, n); 
} 

return Encoding.UTF8.GetString(data, 0, n); 

您還可以在打開FileStream時使用FileOptions.Asynchronous | FileOptions.SequentialScan。 SequentialScan標誌指示文件將從頭到尾按順序訪問。系統可以將此用作提示來優化文件緩存。

看到你想要的審查也this link