KMC
KMC

Reputation: 20046

Remove the null line in a text file

I like to export a text file to be read by some PLC which could not process empty or null lines. The \r\n in WriteLine generate a null line at the end of the text file, and I could not figure a way to not generate it or to remove it.

This is how I generate and write the lines:

List<string> lines = new List<string>();
lines.Add(...);
foreach (string line in lines)
{
    file.WriteLine(line);
}

I tried removing the line with the following code but the end null line remains:

List<string> lines = File.ReadAllLines(path).Where(arg => !string.IsNullOrWhiteSpace(arg)).ToList();
File.WriteAllLines(path, lines);

I also tried deleting the last line, but of course it remove the last line instead of the carriage return..

lines = lines.GetRange(0, lines.Count - 1);

The image demonstrate pictorially the issue (left) and what I like to achieve (right)

enter image description here

Upvotes: 1

Views: 1614

Answers (4)

ephraim
ephraim

Reputation: 436

Here's your sollution:

  var lst = new List<string> { "jkl", "rueioqwp", "JKL:", "reqwdasf" };

   for (int i = 0; i < lst.Count; i++)
       {
            string newLine = "";
            if (i != lst.Count - 1)
                newLine = Environment.NewLine;
            File.AppendAllText("c:\\temp\\tmp.txt", lst[i] + newLine);
        }

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101731

Not generating the blank line at the first place will solve your problem, since you are calling WriteLine each time, it adds \r\n to the end of each line, including the last one. You can use a for loop instead and check if you are writing the last line, call Write method instead of WriteLine:

for(int i=0; i < lines.Length; i++)
{
    if(i == lines.Length - 1)
    {
        file.Write(line);
    }
    else 
    {
        file.WriteLine(line);
    }
}

Upvotes: 5

Jay
Jay

Reputation: 338

If you also want to remove lines that only contain whitespace, use


resultString = Regex.Replace(subjectString, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);

^\s+$ will remove everything from the first blank line to the last (in a contiguous block of empty lines), including lines that only contain tabs or spaces.

[\r\n]* will then remove the last CRLF (or just LF which is important because the .NET regex engine matches the $ between a \r and a \n, funnily enough)

Upvotes: 0

Lanorkin
Lanorkin

Reputation: 7534

Whenever you use WriteLine, it adds end-of-line to the end

What you need it to avoid last end-of-line, by using Write instead of WriteLine

For example:

file.Write(string.Join(Environment.NewLine, lines));

Upvotes: 2

Related Questions