我正在尝试用 C# 编写一个程序,它将包含多个联系人的 vCard (VCF) 文件拆分为每个联系人的单独文件。我知道 vCard 需要保存为 ANSI (1252) 以便大多数手机读取它们。
但是,如果我使用 StreamReader
打开一个 VCF 文件,然后使用 StreamWriter
(将 1252 设置为编码格式)将其写回,所有特殊字符如 å
、æ
和 ø
被写成 ?
。 ANSI (1252) 肯定会支持这些字符。我该如何解决这个问题?
编辑:这是我用来读取和写入文件的一段代码。
private void ReadFile()
{
StreamReader sreader = new StreamReader(sourceVCFFile);
string fullFileContents = sreader.ReadToEnd();
}
private void WriteFile()
{
StreamWriter swriter = new StreamWriter(sourceVCFFile, false, Encoding.GetEncoding(1252));
swriter.Write(fullFileContents);
}
最佳答案
您假设 Windows-1252 支持上面列出的特殊字符是正确的(有关完整列表,请参阅 Wikipedia entry)。
using (var writer = new StreamWriter(destination, true, Encoding.GetEncoding(1252)))
{
writer.WriteLine(source);
}
在我的测试应用程序中使用上面的代码产生了这个结果:
看看我能写出多么酷的字母:å、æ 和 ø!
找不到问号。使用 StreamReader
读取时是否设置了编码?
编辑:
您应该能够使用 Encoding.Convert
将 UTF-8 VCF 文件转换为 Windows-1252。不需要 Regex.Replace
。以下是我的做法:
// You might want to think of a better method name.
public string ConvertUTF8ToWin1252(string source)
{
Encoding utf8 = new UTF8Encoding();
Encoding win1252 = Encoding.GetEncoding(1252);
byte[] input = source.ToUTF8ByteArray(); // Note the use of my extension method
byte[] output = Encoding.Convert(utf8, win1252, input);
return win1252.GetString(output);
}
这是我的扩展方法的样子:
public static class StringHelper
{
// It should be noted that this method is expecting UTF-8 input only,
// so you probably should give it a more fitting name.
public static byte[] ToUTF8ByteArray(this string str)
{
Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(str);
}
}
关于c# - 将 Unicode 转换为适用于电子名片的 Windows-1252,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4351985/