日期:2014-05-20  浏览次数:20845 次

请问,ReadLine方法读取文件
一个txt文件,有两行
aaaa
bbbb

代码:
string s1 = @"D:\iosample\pp.txt";
using (StreamReader sr = new StreamReader(s1))
  {
  Console.WriteLine(sr.ReadLine());
  }

输出结果为aaaa
我想问的是:
ReadLine方法的返回值是流中的下一行,而下一行是bbbb,那返回值应该是bbbb啊?应该输出bbbb吧

MSDN

------解决方案--------------------
StreamReader刚建立的时候, 当前位置是0,下一行就是第一行。

using (StreamReader sr = new StreamReader(s1))
{
Console.WriteLine(sr.ReadLine()); //第一行
Console.WriteLine(sr.ReadLine()); //第二行
}

ReadLine可以理解为一行一行读取。如果一上来就返回第二行,那第一行怎么办
------解决方案--------------------
你的msdn连接中不是有循环读取的代码吗

C# code

using (StreamReader sr = new StreamReader(path)) 
            {
                while (sr.Peek() >= 0) 
                {
                    Console.WriteLine(sr.ReadLine());
                }
            }

------解决方案--------------------
没有循环,只能取到第一行
------解决方案--------------------
while (sr.Peek() >= 0) 
你贴出来的例子,你不仔细看看吗?

------解决方案--------------------
using (StreamReader sr = new StreamReader(s1))
{

while (!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}


------解决方案--------------------
C# code
string path = @"D:\1.txt";//读取文件txt
            string sLine=string.Empty;
            using (StreamReader sr = new StreamReader(path))//遍历数据
            {
                while (!sr.EndOfStream)//不是末尾数据
                {
                    sLine = sr.ReadLine();
                    if (sLine.Length < 1)
                    {
                        continue;
                    }
                }
            }
              textBox1.Text = sLine.ToString();

------解决方案--------------------
阅读器初始时指向文件的开头,每执行一次ReadLine()读取一行,

BOF:开头
文件内容
EOF:结尾

开头、结尾没有任何行,可以认为阅读器初始时指向BOF。
------解决方案--------------------
引用百度百科:

Before Of File
  Before of File,在电脑的术语缩写通常为 BOF,在作业系统决定资料源无更多的资料可读取。资料源通常称为档案或串流。   bof 用于指在第一条记录的前面,当记录集为空是,bof和eof都为true。


------解决方案--------------------
循环读取文件内容呢

------解决方案--------------------
探讨
你的msdn连接中不是有循环读取的代码吗


C# code

using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.WriteLine……

------解决方案--------------------
你并没有做循环啊。。他读的就是第一行的内容。