user198003
user198003

Reputation: 11151

Read last empty line of a text file

I have funny problem - I tried several scripts that will read text files, and that's ok.

Problem occur when text file have empty line at the end - that line is "ignored".

Code I use is "usual" code for file read, like next one:

string fullFileName;
fullFileName = "myFile.txt";
var lines = File.ReadAllLines(fullFileName);
string fileContent = null;
bool firstLine = true;

foreach (var line in lines) {
    if (firstLine != true)
    {
        //textBox1.Text += System.Environment.NewLine;
        fileContent += System.Environment.NewLine;
    }
    else
    {
        firstLine = false;
    }
    //textBox1.Text += line;
    fileContent += line;
}

textBox1.Text = fileContent;

So, if last line of file myFile.txt is empty, it is not showed in a TextBox.

Can you help me where is a problem?

Upvotes: 3

Views: 2404

Answers (4)

MAK
MAK

Reputation: 615

File.ReadAllLines(fullFileName);

does not reads carriage return ('\r'). i think your last line contains only carriage return thats why its not being read. put space in last line to check.

http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx

Upvotes: 0

sara
sara

Reputation: 3934

It is a problem with the file representation, not with ReadAllLines. See this thread: http://www.pcreview.co.uk/forums/file-readalllines-doesnt-read-last-blank-line-weird-t3765200.html

Upvotes: 1

Odrai
Odrai

Reputation: 2353

Other solution:

using (FileStream fileStream = File.OpenRead("C:\myFile.txt"))
using (StreamReader streamReader = new StreamReader(fileStream))
{
    string fileContent = streamReader.ReadToEnd();

    textBox1.Text = fileContent;
}

Upvotes: 0

Matthew Watson
Matthew Watson

Reputation: 109597

I think you could avoid the loop altogether and just do:

textBox1.Text = File.ReadAllText(fullFileName);

This will preserve all the newlines.

Upvotes: 5

Related Questions