c#从文本文件中读取

时间:2013-09-06 08:40:10

标签: c# arrays list

我正在阅读一个有一些格式的文本文件。我正在跳过前两行,然后读取firstname,second name,然后创建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

2 个答案:

答案 0 :(得分:2)

出了什么问题,无论文档是否有下一行,都会执行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));
       }
   }
}

答案 1 :(得分:1)

您可以为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());
}
你可以看到帖子:

how to remove empty line when reading text file using C#