繁体   English   中英

C#从文本文件读取

[英]c# reading from a text file

我正在阅读具有某种格式的文本文件。 我跳过了前两行,然后读取了firstname,secondname,然后创建了一个firstname,secondname的列表。 一切正常,但最后一行为空时,我的程序停止工作并给出错误。 如何避免whiltespace,以便我的程序不停止我的代码,是:

public void Read(string filename, List<Person> person)
{
   using (StreamReader sr = new StreamReader(filename))
   {
       sr.ReadLine();
       sr.ReadLine();
       while (!sr.EndOfStream)
       {
           FirstName= sr.EndOfStream ? string.Empty : sr.ReadLine();
           LastName= sr.EndOfStream ? string.Empty : sr.ReadLine();
           person.Add(new Person(FirstName, LastName));
       }
   }
}

文件格式为

Students Data
Description
FirstName
LastName
FirstName
LastName
FirstName
LastName
FirstName
LastName

出问题了,无论文档是否有下一行,都将执行sr.ReadLine() ,因此它可能返回null(如果您用完了所有行),只需检查sr.ReadLine()返回null

public void Read(string filename, List<Person> person)
{
   using (StreamReader sr = new StreamReader(filename))
   {
       sr.ReadLine();
       sr.ReadLine();
       while (!sr.EndOfStream)
       {
           String FirstName = sr.ReadLine() ?? "-not defined-";
           String LastName = sr.ReadLine() ?? "-not defined-";

           person.Add(new Person(FirstName, LastName));
       }
   }
}

您可以为StreamReader类创建一个适配器,如下所示

public class NoBlankStreamReader : StreamReader
{
    public NoBlankStreamReader(FileStream fs) : base(fs) { }


    private bool IsBlank(string inString)
    {
        if (!string.IsNullOrEmpty(inString)) inString = inString.Trim();
        return string.IsNullOrEmpty(inString);
    }


    public override string ReadLine()
    {
        string result= base.ReadLine();
        while (result!=null && IsBlank(result))
            result = base.ReadLine();
        return result;
    }
}

然后像这样使用:

using (FileStream fs=File.OpenRead(@"test.txt"))
using (TextReader reader = new NoBlankStreamReader(fs))
{
    while (reader.Peek() > -1)
        Console.WriteLine(reader.ReadLine());
}

或者您可以看到该帖子:

使用C#读取文本文件时如何删除空行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM