File encoding doesn't work

梦想的初衷 提交于 2019-12-11 08:48:42

问题


In my code

string[] Lines = reactor.GetMergedLines();
string fileName = "foo.bar";
StreamWriter sw = new StreamWriter(File.Open(fileName, FileMode.CreateNew), Encoding.GetEncoding(28605));
foreach (string line in Lines)
{
    sw.WriteLine(line);
}
sw.Close();

the file, which gets created is not encoded with the given codepage. Lines is filled with strings out of an iso-8859-1-file. I tried it with the code page number Encoding.GetEncoding(28605), it's name Encoding.GetEncoding("ISO-8859-15") and with File.WriteAllLines(fileName, Lines, Encoding.GetEncoding(28605)) instead of StreamWriter. But if I take a look at the file with cygwin file -bi [filename], it tells me, the encoding would be "us-ascii". Also, some characters aren't encoded properly and replaced by question marks.

How to write out a text file in C# with a code page other than utf-8? didn't helped, as you can see.

What is the problem?


回答1:


You can use other overloads of Encoding.GetEncoding to handle all cases when an Unicode character can't be converted to your target code page. More information on this MSDN topic. The same could be achieved if you explicitly set the Encoding.EncoderFallback property (link to MSDN).

For example you can use the following to throw an exception every time when conversion of one Unicode character fails:

Encoding enc = Encoding.GetEncoding(28605, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);

Note: The default EncoderFallback is System.Text.InternalEncoderBestFitFallback which produces question marks for unknown code points.



来源:https://stackoverflow.com/questions/22982718/file-encoding-doesnt-work

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