I have the following code in C# that writes an array of lines to a file. The difference between this and File.WriteAllLines(string, string[]);
is that mine does not leave an extra newline at the end.
public static void WriteAllLinesCompact(string path, IEnumerable<string> contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
bool isFirst = true;
using (FileStream stream = File.OpenWrite(path))
using (StreamWriter writer = new StreamWriter(stream))
{
foreach (string line in contents)
{
if (isFirst)
{
writer.Write(line);
isFirst = false;
continue;
}
writer.Write("\r\n" + line);
}
}
}
The problem is that it does not terminate the file after the last line. For example, if the last line was "text = absolute", after replacing the last line with "tempor" and saving using the above method, the file's last line would be "tempor absolute" instead of just "tempor".
Please let me know if you need more information.
EDIT : I will try to explain more clearly what happens in the replace process.
Step 1 : Load any .txt file with File.ReadAllLines(string);
Step 2 : Replace the last line with one that's shorter than the previous one. For example, if the length of the last value was 10 chars, the new one should perhaps be 7 chars.
Step 3 : Save using the given method to the same file as before.