問題描述
我正在嘗試用 C# 編寫一個程序,該程序會將包含多個聯(lián)系人的 vCard (VCF) 文件拆分為每個聯(lián)系人的單獨文件.我知道大多數(shù)手機需要將電子名片保存為 ANSI (1252) 才能讀取它們.
I am trying to write a program in C# that will split a vCard (VCF) file with multiple contacts into individual files for each contact. I understand that the vCard needs to be saved as ANSI (1252) for most mobile phones to read them.
但是,如果我使用 StreamReader
打開一個 VCF 文件,然后使用 StreamWriter
(設(shè)置 1252 作為編碼格式)將其寫回,所有特殊字符如 ?
、?
和 ?
被寫成 ?
.ANSI (1252) 肯定會支持這些字符.我該如何解決這個問題?
However, if I open a VCF file using StreamReader
and then write it back with StreamWriter
(setting 1252 as the Encoding format), all special characters like ?
, ?
and ?
are getting written as ?
. Surely ANSI (1252) would support these characters. How do I fix this?
這是我用來讀寫文件的一段代碼.
Here's the piece of code I use to read and write the file.
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);
}
推薦答案
您正確地假設(shè) Windows-1252 支持上面列出的特殊字符(有關(guān)完整列表,請參閱 維基百科條目).
You are correct in assuming that Windows-1252 supports the special characters you listed above (for a full list see the Wikipedia entry).
using (var writer = new StreamWriter(destination, true, Encoding.GetEncoding(1252)))
{
writer.WriteLine(source);
}
在我使用上面代碼的測試應(yīng)用程序中,它產(chǎn)生了這個結(jié)果:
In my test app using the code above it produced this result:
看看我能寫出的很酷的字母:?、? 和 ?!
找不到問號.使用 StreamReader
讀取時是否設(shè)置了編碼?
No question marks to be found. Are you setting the encoding when your reading it in with StreamReader
?
您應(yīng)該能夠使用 Encoding.Convert
將 UTF-8 VCF 文件轉(zhuǎn)換為 Windows-1252.不需要 Regex.Replace
.這是我的做法:
You should just be able to use Encoding.Convert
to convert the UTF-8 VCF file into Windows-1252. No need for Regex.Replace
. Here is how I would do it:
// 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);
}
這是我的擴展方法的外觀:
And here is how my extension method looks:
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);
}
}
此外,您可能還想添加using
s 到您的 ReadFile
和 WriteFile
方法.
Also you'll probably want to add using
s to your ReadFile
and WriteFile
methods.
這篇關(guān)于將 Unicode 轉(zhuǎn)換為用于 vCard 的 Windows-1252的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!