Search code examples
c#.netstreamreader

C# reads text file line as empty lines


The code:

public static void Read()
{
    StreamReader DBF = new StreamReader(path);
    string line;
    while ((line = DBF.ReadLine()) != null)
    {
        Console.WriteLine(">", line);
    }
    DBF.Close();
}

The file content:

|_-|-_|
text

The output:

>
>

I tried also declare charset, its doesn't help:

StreamReader DBF = new StreamReader(path, System.Text.Encoding.UTF8);

Text file has UTF-8 charset and uses CRLF. Why does C# reads strings from file as empty strings? Program read file properly once before.


Solution

  • Well, in your current implementation

    Console.WriteLine(">", line);
    

    ">" means format; see Console.WriteLines for details. You can either turn ">" into a format string, e.g. ">{0}", note placeholder {0} - position where 0th argument (which isline) will be placed:

    Console.WriteLine(">{0}", line);
    

    Or get rid of format at all:

    Console.WriteLine(">" + line);