Question

I would like to pre-pend(to the beginning) a file with a string in C#. Currently, I am just replacing content of the file with my string plus original content. I DO NOT WANT TO DO THIS, because streamwriter will mess-up encoded characters.

Is there a way to pre-pend a text file without changing it's original encoding(of each character).

There is gotta be a way.

Was it helpful?

Solution

The code at the bottom of this page appears to let you Read a file in, retain the encoding and then write it back out using the same encoding. You should be able to modify this to do what you need.

OTHER TIPS

Text encoding is a funny thing. If you are writing code that is going to be interpreted as encoded characters, the compiler must be told (or it might assume) how the bytes ought to be arranged to represent particular characters. If your program is agnostic of the encoding of the files with which you will be working, then how do you intend to indicate to the compiler how it should interpret the array of bytes in that file?

You could consider reading the characters as a stream of bytes instead of a stream of characters if you don't know how to instruct the compiler to interpret those bytes (i.e. you don't know what encoding will be used at run-time). In that case, you have to hope that whatever basic characters you chose to append to the beginning of the file can be universally recognized in any encoding; this is because you will be appending bytes and not characters to the beginning of the file.

Just read the file without ever decoding the bytes. And you have to choose an encoding for your header - ASCII seems to be the safest choice in your situation.

const String fileName = "test.file";
const String header = "MyHeader";

var headerBytes = Encoding.ASCII.GetBytes(header);
var fileContent = File.ReadAllBytes(fileName);

using (var stream = File.OpenWrite(fileName))
{
    stream.Write(headerBytes, 0, headerBytes.Length);
    stream.Write(fileContent, 0, fileContent.Length);
}

Note that the code directly operates on the stream and does not use a TextReader or TextWriter (this are the abstract base classes of StreamReader and StreamWriter). You can use a BinaryReader and BinaryWriter to simplify accessing the stream if you have to deal with tasks complexer then just reading and writing array.

I found this which let's me get correct encoding of the file: http://www.personalmicrocosms.com/Pages/dotnettips.aspx?c=15&t=17

then I can use that encoding in the streamwriter.

Is it safe to use?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top