c# - 将 Unicode 转换为适用于电子名片的 Windows-1252

标签 c# .net unicode character-encoding windows-1252

我正在尝试用 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);
    }
}

您可能还需要 add usings to your ReadFile and WriteFile methods.

关于c# - 将 Unicode 转换为适用于电子名片的 Windows-1252,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4351985/

相关文章:

c# - 将某些文件嵌入到dll中是错误的吗?

C# 从另一个方法调用事件 (linkLabel2_LinkClicked)

c# - 将日志文件的日期转换为字符串,然后将数据库的字符串转换为日期时间

c# - 在 UI 线程中任务完成时显示表单

unicode - 从 unicode 字符串中获取随机表情符号/字符

unicode - 如何在 NSIS 自定义页面中编写波斯语?

javascript - 使用 JavaScript 将文本从一个文本框发送到另一个文本框

.net - iTextSharp 中的 Unicode 符号

delphi - 获取程序可执行文件的名称(如 paramstr(0) 中),但在 Delphi 7 中将其作为 Unicode 字符串获取?

c# - 为什么我可以将 0.0 分配给枚举值,而不是 1.0