Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET File.WriteAllLines leaves empty line at the end of file

Tags:

arrays

.net

line

When I'm saving content of the String[] array with System.IO.File.WriteAllLines, at the end of a file is always left a blank line. For example:

System.IO.File.WriteAllLines(Application.dataPath + "/test.txt",["a", "b", "c"]);

Produces file (without underscore):

a
b
c
_

There was already such topic: Empty line in .Net File.WriteAllLines, is a bug? , but autor said that "I think there are something wrong with my data,that's my problem but not the WritAllLines" and it was closed as "too localized" (?!?).

It's a bug? How can I easily get rid of it (for now I'm just ignoring it when reading file again)?

like image 475
user1557862 Avatar asked Jul 27 '12 14:07

user1557862


Video Answer


2 Answers

You can also save a file with WriteAllText and join array of lines manually like:

File.WriteAllText(file, String.Join("\r\n",correctedLines));
like image 59
Paweł Zarzycki Avatar answered Oct 03 '22 19:10

Paweł Zarzycki


There's a simpler workaround:

// 1. Convert the items on the array to single string with the separator "\n" between the items
string AllItemsInOneString= string.Join("\n", StringArrayToSave);

// 2. Save with WriteAllText instead
File.WriteAllText(FilePath, AllItemsInOneString);
like image 24
Majid ALSarra Avatar answered Oct 03 '22 19:10

Majid ALSarra