我正在尝试使用 C#编写一个程序,该程序将具有多个联系人的vCard(VCF)文件拆分为每个联系人的单独文件。我知道vCard需要保存为ANSI(1252),以便大多数手机读取它们。

但是,如果我使用StreamReader打开VCF文件,然后使用StreamWriter写回(将1252设置为Encoding格式),则所有特殊字符(如åæø)都将写为?。当然,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);
}
在我的测试应用程序中,使用上面的代码产生了以下结果:Look at the cool letters I can make: å, æ, and ø!找不到问号。使用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);
    }
}

另外,您可能想要add using s to your ReadFile and WriteFile methods.

10-08 14:23