将vcards转换为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条目 )。
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); } }
此外,您可能希望将s添加到ReadFile
和WriteFile
方法中。