简体   繁体   English

文件编码不起作用

[英]File encoding doesn't work

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. 行由iso-8859-1-文件中的字符串填充。 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. 我尝试使用代码页号Encoding.GetEncoding(28605) ,它的名称是Encoding.GetEncoding("ISO-8859-15")以及File.WriteAllLines(fileName, Lines, Encoding.GetEncoding(28605))而不是StreamWriter。 But if I take a look at the file with cygwin file -bi [filename] , it tells me, the encoding would be "us-ascii". 但是,如果我用cygwin file -bi [filename]来查看文件,它会告诉我,编码将是“ 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? 如何用utf-8以外的代码页用C#编写文本文件? didn't helped, as you can see. 如您所见,它没有帮助。

What is the problem? 问题是什么?

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. 您可以使用Encoding.GetEncoding其他重载来处理无法将Unicode字符转换为目标代码页的所有情况。 More information on this MSDN topic . 有关此MSDN主题的更多信息。 The same could be achieved if you explicitly set the Encoding.EncoderFallback property ( link to MSDN ). 如果您显式设置Encoding.EncoderFallback属性( 链接到MSDN ),则可以实现相同的效果。

For example you can use the following to throw an exception every time when conversion of one Unicode character fails: 例如,每次转换一个Unicode字符失败时,可以使用以下语句引发异常:

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. 注意:默认的EncoderFallbackSystem.Text.InternalEncoderBestFitFallback ,它为未知的代码点生成问号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM