Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Text File Encoding

Tags:

c#

notepad++

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);
}
like image 204
MasterOfStupidQuestions Avatar asked Mar 01 '26 21:03

MasterOfStupidQuestions


2 Answers

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));
like image 121
Raphaël Althaus Avatar answered Mar 03 '26 11:03

Raphaël Althaus


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.

like image 37
Richard Avatar answered Mar 03 '26 09:03

Richard