Change Text File Encoding

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);
}

Upvotes: 3

Views: 14227

Answers (2)

Richard
Richard

Reputation: 109180

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.

Upvotes: 1

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

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));

Upvotes: 6

Related Questions