Change Text File Encoding

瘦欲@ 提交于 2020-03-23 23:23:40

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/20973023/change-text-file-encoding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!