文件编码不起作用 [英] File encoding doesn't work

查看:221
本文介绍了文件编码不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  string [] Lines = reactor.GetMergedLines(); 
string fileName =foo.bar;
StreamWriter sw = new StreamWriter(File.Open(fileName,FileMode.CreateNew),Encoding.GetEncoding(28605));
foreach(行中的字符串)
{
sw.WriteLine(line);
}
sw.Close();

创建的文件不会使用给定的代码页进行编码。线条用iso-8859-1文件中的字符串填充。我尝试使用代码页码,它的名称 Encoding.GetEncoding(ISO-8859-15) File.WriteAllLines(fileName,Lines,Encoding.GetEncoding(28605))而不是StreamWriter。但是,如果我使用cygwin file -bi [filename] 查看文件,它告诉我,编码将是us-ascii。此外,一些字符未被正确编码,并被问号替换。



如何用除utf-8之外的代码页写出C#中的文本文件?没有帮助,因为你可以



有什么问题?

解决方案

您可以使用其他重载 Encoding.GetEncoding 来处理Unicode字符无法转换为目标代码页时的所有情况。有关此 MSDN主题的详细信息。
如果您明确地设置了 Encoding.EncoderFallback 属性(链接到MSDN )。



例如,您可以使用以下内容来抛出每次转换一个Unicode字符失败时都会出现异常:

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

注意:默认的 EncoderFallback System.Text.InternalEncoderBestFitFallback 会产生未知代码点的问号。


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?

解决方案

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.

这篇关于文件编码不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆