how to remove empty line when reading text file us

2020-06-06 07:27发布

i have text file and read it using stream reader, when my file is having empty line along with data, it does not read any thing. how to remove the empty line using C#.

标签: c#
3条回答
狗以群分
2楼-- · 2020-06-06 08:17

You haven't shown any code, and your description is pretty woolly, but as of .NET 4 this would be a very easy way to do what you want:

IEnumerable<string> lines = File.ReadLines().Where(line => line != "");

Note that it won't perform any trimming, so a line with only spaces in would still be returned.

Also note that the code above doesn't read the file when you just execute that line - it will only read it when you try to iterate over lines, and will read it again every time you iterate over lines. If you want to read it into memory all in one go, you might want:

List<string> lines = File.ReadLines().Where(line => line != "").ToList();
查看更多
地球回转人心会变
3楼-- · 2020-06-06 08:19

Below is the code:

private void ReadFile()
{
    try
    {
        string line = null;
        System.IO.TextReader readFile = new StreamReader("C:\\csharp.net-informations.txt");
        while (true)
        {
            line = readFile.ReadLine();
            if (line != null)
            {
                MessageBox.Show(line);
            }
        }
        readFile.Close();
        readFile = null;
    }
    catch (IOException ex)
    {
        MessageBox.Show(ex.ToString());
    }
}
查看更多
贼婆χ
4楼-- · 2020-06-06 08:23

Well, you should use the method "ReadLine()" from the StreamReader in a loop. When you receive an empty line, simply check if the string obtained from ReadLine() is empty. If it is, ignore the line. Try something like:

    StreamReader input = new StreamReader("...");
    String line = null;

    do 
    {
    line = input.ReadLine();

    if (line == null)
    {
    return;
    }

    if (line == String.Empty)
    {
    continue;
    }

    // Here you process the non-empty line

    } while (true);
查看更多
登录 后发表回答