简体   繁体   English

C#从文本文件读取

[英]c# reading from a text file

I am reading a text file which has some format. 我正在阅读具有某种格式的文本文件。 I am skipping the first two lines and then reading firstname, second name and then creating a list of firstname , secondname. 我跳过了前两行,然后读取了firstname,secondname,然后创建了一个firstname,secondname的列表。 Everything is working file but when the last line is empty then my program stops working and gives an error. 一切正常,但最后一行为空时,我的程序停止工作并给出错误。 How to avoid whiltespace so that my program dont stop my code is: 如何避免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));
       }
   }
}

File format is 文件格式为

Students Data
Description
FirstName
LastName
FirstName
LastName
FirstName
LastName
FirstName
LastName

What is going wrong, is that sr.ReadLine() will be executed regardless of whether the document has a next line or not, so it might return null (if you've run out of lines) Simply check whether sr.ReadLine() returns null 出问题了,无论文档是否有下一行,都将执行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));
       }
   }
}

You could create an adapter for the StreamReader class, something like this 您可以为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;
    }
}

then use like this: 然后像这样使用:

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

or u can see the post: 或者您可以看到该帖子:

how to remove empty line when reading text file using C# 使用C#读取文本文件时如何删除空行

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

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