2013-04-24 152 views
0

我已經爲自己編寫了一個小程序,用於讀取相當大的日誌文件(只是純文本和數字)並將它們寫入文本框(notepadish thingy)。C#打開文件

我使用這種方法讀取文件,雖然它做的竅門,我想知道是否有一些方法來優化它,如果當前正在讀取的文件被鎖定,而不會被寫入而讀取它(因爲它的日誌不斷更新的文件對我不利)。

private void ReadFile(string path) 
    { 
     using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
     using (StreamReader reader = new StreamReader(file)) 
     { 
      StringBuilder sb = new StringBuilder(); 
      string r = reader.ReadLine(); 

      while (r != null) 
      { 
       sb.Append(r); 
       sb.Append(Environment.NewLine); 
       r = reader.ReadLine(); 
      } 
      textBox.Text = sb.ToString(); 
      reader.Close(); 
     } 
    } 
+1

['File.ReadAllText'](http://msdn.microsoft.com/en-us/library/system.io.file.readalltext.aspx)? – 2013-04-24 14:39:24

+0

@UweKeim如果文件正在被另一個進程寫入,它將不起作用。 OP的代碼看起來很好。 – I4V 2013-04-24 14:40:20

+1

您可以用'sb.AppendLine'調用替換兩個'Append'調用。 – 2013-04-24 14:43:42

回答

1

我發現在貼here問題的夫婦建議,你的代碼已經確認的第一個建議,所以我會嘗試使用

File.OpenRead(path) 

並看看是否適合你。

如果不是這樣,顯然寫入該文件的程序根本不會讓您讀取它,只要它具有句柄即可。您可能會注意到FileShare.ReadWrite告訴系統其他程序可能對文件做什麼,編寫日誌的程序可能根本不允許您甚至讀取文件。

+0

我只是從中讀取數據並在文本框中查看結果。 – perkrlsn 2013-04-24 14:42:38

+0

@perkrlsn這是寫給它的另一個程序嗎? – 2013-04-24 14:43:21

+0

寫入日誌文件不在我的範圍之內。我只是想將它讀入我的小程序中,而不是將它鎖定在處理該程序的進程中。 – perkrlsn 2013-04-24 14:45:53

0

試試這個:

using System; 
using System.IO; 

namespace csharp_station.howto 
{ 
    class TextFileReader 
    { 
     static void Main(string[] args) 
     { 
      // create reader & open file 
      Textreader tr = new StreamReader("date.txt"); 

      // read a line of text 
      Console.WriteLine(tr.ReadLine()); 

      // close the stream 
      tr.Close(); 

      // create a writer and open the file 
      TextWriter tw = new StreamWriter("date.txt"); 

      // write a line of text to the file 
      tw.WriteLine(DateTime.Now); 

      // close the stream 
      tw.Close(); 
     } 
    } 
} 

這將是做到這一點的最簡單的方法。我認爲你的代碼對我來說看起來很好。通過將日誌文件讀入文本框中,我看不到問題。您可以嘗試使用威脅做simutanously ....