简体   繁体   中英

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. 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:

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

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

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#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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