2013-03-27 75 views
2

我正在開發一個C#應用程序,我需要從文本文件中讀取一行並返回到第一行。從文本文件中讀取一行並返回

由於文件大小可能過大,我無法將其複製到數組中。

我想這個代碼

StreamReader str1 = new StreamReader(@"c:\file1.txt"); 
StreamReader str2 = new StreamReader(@"c:\file2.txt"); 

int a, b; 
long pos1, pos2; 

while (!str1.EndOfStream && !str2.EndOfStream) 
{ 
    pos1 = str1.BaseStream.Position; 
    pos2 = str2.BaseStream.Position; 

    a = Int32.Parse(str1.ReadLine()); 
    b = Int32.Parse(str2.ReadLine()); 
    if (a <= b) 
    { 
     Console.WriteLine("File1 ---> " + a.ToString()); 
     str2.BaseStream.Seek(pos2, SeekOrigin.Begin); 
    } 
    else 
    { 
     Console.WriteLine("File2 ---> " + b.ToString()); 
     str1.BaseStream.Seek(pos1, SeekOrigin.Begin); 
    } 
} 

當我debuged我發現str1.BaseStream.Positionstr2.BaseStream.Position在每一個循環相同的程序,所以不會有任何變化。

有沒有更好的方法?

感謝

回答

0

另一種我更喜歡使用的方式。

創建這樣一個功能:

string ReadLine(Stream sr,bool goToNext) 
     {    
      if (sr.Position >= sr.Length) 
       return string.Empty;    
      char readKey; 
      StringBuilder strb = new StringBuilder(); 
      long position = sr.Position; 
      do 
      { 
       readKey = (char)sr.ReadByte(); 
       strb.Append(readKey); 
      } 
      while (readKey != (char)ConsoleKey.Enter && sr.Position<sr.Length); 
      if(!goToNext) 
      sr.Position = position; 
      return strb.ToString();   
     } 

然後,從文件創建流爲它的參數

Stream stream = File.Open("C:\\1.txt", FileMode.Open); 
7

可以使用ReadLines大文件,它是延遲執行和整個文件不會加載到內存中,這樣你就可以在IEnumerable類型中的臺詞:

var lines = File.ReadLines("path"); 

如果你在舊的.NET版本,下面是如何自己構建ReadLines

public IEnumerable<string> ReadLine(string path) 
    { 
     using (var streamReader = new StreamReader(path)) 
     { 
      string line; 
      while((line = streamReader.ReadLine()) != null) 
      { 
       yield return line; 
      } 
     } 
    } 
+0

謝謝,有什麼辦法與讀出整個文件做呢? – Arashdn 2013-03-27 11:29:15

+0

@Arashdn:你嘗試過這種方式嗎?這種方式不讀取整個文件 – 2013-03-27 11:34:49

+0

我使用舊版本的.net,它不包含File.ReadLines – Arashdn 2013-03-27 11:38:10