3

How do you change a text files encoding through code? I am using this code to actually create the file itself, but how can I change the encoding (change to UTF-8 w/o BOM)

string path = @"E:\Test\Example.txt";
if (!File.Exists(path))
{
    File.Create(path);
}
2
  • 4
    THe file does not have an encoding, the text you write into it has.
    – okrumnow
    Jan 7, 2014 at 13:35
  • Is there a way to change the encoding of the text via code? Jan 7, 2014 at 13:36

2 Answers 2

6

You could do something like that, but I'm not sure this makes really sense, as it seems you have no content in your file...

If you have a content, replace string.Empty by the content

File.WriteAllText(path, string.Empty, Encoding.GetEncoding(<someEncodingCode>));

Edit :

File.WriteAllText(path, string.Empty, new UTF8Encoding(false));
1
1

First, except in a few bases (eg. a Unicode BOM, XML's encoding rules) you will need some form of metadata to tell you the current encoding. While some tools will make a guess they are not reliable (eg. the various Latin encodings in ISO/IEC 8859-1 don't have anything to distinguish them).

Once you know the input encoding, pass an instance of Encoding, created with the name of the encoding, to the StreamReader constructor, create an instance of StreamWriter with the desired output encoding and then pump strings from one to another.

(If you know the files are not too large: read everything in one go with File.ReadAllTetxt and write with File.WriteAllText, which take Encoding parameters.

1
  • The data was going to be manually cut/paste into the text file, just wanted it to be auto created. -- Which I now see that the text is what has the encoding, not the file, so your answer makes sense now. Jan 7, 2014 at 13:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.