从文本文件中读取一行并返回

问题描述:

我正在开发一个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在每一个循环相同的程序,所以不会有任何变化。

有没有更好的方法?

感谢

另一种我更喜欢使用的方式。

创建这样一个功能:

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); 

可以使用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