Tutorial :(C# WinFoms) Writing files and New line



Question:

I'm making changes to a file, the 'source' file is a plain text file, but from a UNIX system.

I'm using a StreamReader to read the 'source' file, I then make and store the changes to a StringBuilder using AppendLine().

I then create a StreamWriter (set-up with the same Encoding as the StreamReader) and write the file.

Now when I compare the two files using WinMerge it reports that the carriage return characters are different.

What should I do to ensure that the carriage return characters are the same for the type of file that I am editing?

It should also be noted that the files that are to be modified could come from any system, not just from a UNIX system, they could equally be from a Windows system - so I want a way of inserting these new lines with the same type of carriage return as the original file

Thanks very much for any and all replies.

:)


Solution:1

The type of line ending used by a file is independent of the encoding. It sounds like you may need to read the source file to determine the line endings to start with (which you have to do explicitly; I don't believe there's anything in the framework to give you that information) and then explicitly use that when creating the new file. (Instead of calling AppendLine, call Append with the line itself, and then Append again with the appropriate line terminator for that file.)

Note that a single file can have a variety of line endings - some "\r\n", some "\n" and some "\r", so you'll have to apply appropriate heuristics (e.g. picking the most commonly seen line ending).


Solution:2

First you need to assert what is the newline character for the current file. This can be a problem since a given file can mix different line endings.

Then you can set the NewLine property of your StreamWriter:

StreamWriter sw = new StreamWriter("example.txt");    sw.NewLine = "\r";  

For an interesting read about line endings check out The Great Newline Schism.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »