【问题标题】:Converting Unicode to Windows-1252 for vCards将 Unicode 转换为用于 vCard 的 Windows-1252
【发布时间】:2011-05-20 02:45:31
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您认为 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 usings to your ReadFile and WriteFile methods.

    【讨论】:

    • 我认为 OP 问题的关键是您的最后一个问题:确保读取 VCF 的 StreamReader 具有 1252 编码集。
    • 我在使用StreamReader 读取文件时没有设置编码。而且我几乎使用与您的示例相同的代码。但是输入的 VCF 文件是 UTF-8 格式的。出于某种原因,索尼爱立信的“备份到 MS”功能将 VCF 文件保存为 UTF-8!
    • @Lucas:我搞错了。我使用内置功能备份 SE 和诺基亚手机上的联系人,猜猜看,两者都以 UTF-8 格式保存!在所有这些问题之后,我感觉很糟糕,我错过了它!现在,如果我只是在 UTF-8 模式下使用 StreamReader 打开一个 VCF 文件,然后在 UTF-8 模式下使用 StreamWriter 再次保存它,该文件将保存特殊字符,但是,如果我使用 Notepad2 打开该文件,它会显示“ UTF-8 with Signature”作为编码。我做错了吗?
    • @GPX:维基百科指出 BOM "may cause interoperability problems with existing software that could otherwise handle UTF-8" 。然后它继续给出它可能导致的问题的几个例子。所以基本上 UTF-8 with signature 只是意味着 添加了 BOM
    • @GPX:Notepad2 可能只是通过打开它来添加它。如果您手边有一个 HEX 编辑器/查看器,您可能想在运行程序后立即查看文本文件。如果 BOM 实际上是由 .NET 添加的,那么您始终可以编写代码来检查前三个字节是否为 0xEF, 0xBB, 0xBF,如果是则删除它们。
    猜你喜欢
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 2013-10-10
    • 2011-05-22
    • 1970-01-01
    相关资源
    最近更新 更多