无法将 UTF-8 文件中的特殊字符转换为 ANSI
Unable to convert special characters in UTF-8 file into ANSI
我有一个文件需要阅读,最后需要添加一段文字。
程序因字符“í”而失败。
在以 notepad++ (UTF-8) 编码打开文件时,我可以看到
在我的 C# 代码中,我尝试将其转换为默认编码,但应用程序将其更改为“?”而不是“í”。
示例代码:
string processFilePath = @"D:\Test\File1.txt";
string outfile = @"D:\Test\File2.txt";
using (StreamReader reader = new StreamReader(processFilePath))
{
using (StreamWriter writer = new StreamWriter(outfile, false, Encoding.Default))
{
writer.WriteLine(reader.ReadToEnd());
}
}
我在 SO 上调查了类似的问题(上面截取的代码是此处的修改版本):
UTF-8 to ANSI Conversion using C#
我尝试了“System.Text.Encoding”中可用的不同类型的编码 - ASCII/UTF*/ Default 但我能得到的最好的是“?”而不是“í”。
我也经历过:http://kunststube.net/encoding/,确实学到了很多,但还是无法解决问题。
我得到的是:
我需要的是:
我还缺少什么(如果 System.Text.Encoding.ANSI 存在应该很容易)
MSDN:
StreamReader defaults to UTF-8 encoding unless specified otherwise,
instead of defaulting to the ANSI code page for the current system.
即打开 StreamReader(processFilePath)
时,它采用 UTF-8 格式的数据,但似乎并非如此,即如果源文本是 ANSI,或者很可能 Windows-1252 用于西班牙语,请使用
using (StreamReader reader = new StreamReader(processFilePath, Encoding.GetEncoding(1252)))
{
using (StreamWriter writer = new StreamWriter(outfile, false, Encoding.UTF8))
{
writer.WriteLine(reader.ReadToEnd());
}
}
注意指定 1252 和 UTF8。
P.S。另请注意,StreamWriter 中的 false 不会附加到末尾,but overwrite。
我有一个文件需要阅读,最后需要添加一段文字。
程序因字符“í”而失败。
在以 notepad++ (UTF-8) 编码打开文件时,我可以看到
在我的 C# 代码中,我尝试将其转换为默认编码,但应用程序将其更改为“?”而不是“í”。
示例代码:
string processFilePath = @"D:\Test\File1.txt";
string outfile = @"D:\Test\File2.txt";
using (StreamReader reader = new StreamReader(processFilePath))
{
using (StreamWriter writer = new StreamWriter(outfile, false, Encoding.Default))
{
writer.WriteLine(reader.ReadToEnd());
}
}
我在 SO 上调查了类似的问题(上面截取的代码是此处的修改版本): UTF-8 to ANSI Conversion using C#
我尝试了“System.Text.Encoding”中可用的不同类型的编码 - ASCII/UTF*/ Default 但我能得到的最好的是“?”而不是“í”。
我也经历过:http://kunststube.net/encoding/,确实学到了很多,但还是无法解决问题。
我得到的是:
我需要的是:
我还缺少什么(如果 System.Text.Encoding.ANSI 存在应该很容易)
MSDN:
StreamReader defaults to UTF-8 encoding unless specified otherwise, instead of defaulting to the ANSI code page for the current system.
即打开 StreamReader(processFilePath)
时,它采用 UTF-8 格式的数据,但似乎并非如此,即如果源文本是 ANSI,或者很可能 Windows-1252 用于西班牙语,请使用
using (StreamReader reader = new StreamReader(processFilePath, Encoding.GetEncoding(1252)))
{
using (StreamWriter writer = new StreamWriter(outfile, false, Encoding.UTF8))
{
writer.WriteLine(reader.ReadToEnd());
}
}
注意指定 1252 和 UTF8。
P.S。另请注意,StreamWriter 中的 false 不会附加到末尾,but overwrite。