回 帖 发 新 帖 刷新版面

主题:新手求助:为什么不能读出文件内容?

我用StreamReader读取文本文件的内容,但是下面的程序读出来的却是空值。
但是如果把下面的while的那部分注释掉则就可以读出一行,为什么?????
很晕!      

  public string  TxtRead(string fPath, string fName)
        {
            string s;
            filepn = fPath + fName;
            StreamReader  Sr;
            
            Sr = File.OpenText (filepn);
            s = Sr.ReadLine ();
            while (s != null)
            {
                s = Sr.ReadLine();
            }
            Sr.Close();
            return s;
        }

回复列表 (共6个回复)

沙发

因为被覆盖掉了

一种改法:

public string  TxtRead(string fPath, string fName)
        {
            string s;
            filepn = fPath + fName;
            StreamReader  Sr;
            
            Sr = File.OpenText (filepn);
            s = Sr.ReadLine ();
            while (s != null)
            {
                s += Sr.ReadLine() + "\n";
            }
            Sr.Close();
            return s;
        }

板凳

[quote]因为被覆盖掉了

一种改法:

public string  TxtRead(string fPath, string fName)
        {
            string s;
            filepn = fPath + fName;
            StreamReader  Sr;
            
            Sr = File.OpenText (filepn);
            s = Sr.ReadLine ();
            while (s != null)
            {
                s += Sr.ReadLine() + "\n";
            }
            Sr.Close();
            return s;
        }[/quote]
这样做的结果就是:cpu使用率90%
我觉得是不是while部分造成了死循环??

3 楼

不要用s != null判断是否到结尾
用流的EOF等方法属性来判断

4 楼

谢谢!!

5 楼

string path;//所要读取的文件目录
path = @"C:\新建 文本文档.txt";
StreamReader sr;
sr= File.OpenText(path);
string s = sr.ReadToEnd();//读取所有内容
MessageBox.Show(s);//显示

6 楼

public string  TxtRead(string fPath, string fName)
        {
            string s;
            filepn = fPath + fName;
            StreamReader  Sr;
            
            Sr = File.OpenText (filepn);
            s = Sr.ReadLine ();
            while (s != null)//条件判断错误应该改为while(!sr.EndOfStream)
            {
                s = Sr.ReadLine();//出错了如果最后一行是空行的话读出的就是没数据的效果。应该改为s+=Sr.ReadLine();
            }
            Sr.Close();
            return s;
        }

我来回复

您尚未登录,请登录后再回复。点此登录或注册