首先,从微软官网下载安装包:http://www.microsoft.com/downloads/zh-cn/details.aspx?FamilyID=44CAC7F0-633B-477D-AED2-99AEE642FC10&displaylang=zh-cn。下载下来解压,有7个MSI安装文件。
其中CHSPinYinConv.msi是汉字拼音组件,CHTCHSConv.msi是进行繁简体互转组件。其他的是日语韩语的。
安装完成后在VS里添加引用,分别引用:C:\Program Files()x86\Microsoft Visual Studio International Pack\Simplified Chinese Pin-Yin Conversion Library(拼音)下和C:\Program Files(x86)\Microsoft Visual Studio International Pack\Traditional Chinese to Simplified Chinese Conversion Library and Add-In Tool(繁简互转).
最后就是使用:
/// <summary>
/// 汉字转化为拼音
/// </summary>
/// <param name="str">汉字</param>
/// <returns>全拼</returns>
public static string GetPinyin(string str)
{
string r = string.Empty;
foreach (char obj in str)
{
try
{
ChineseChar chineseChar = new ChineseChar(obj);
string t = chineseChar.Pinyins[0].ToString();
r += t.Substring(0, t.Length - 1);
}
catch
{
r += obj.ToString();
}
}
return r;
}
/// <summary>
/// 汉字转化为拼音首字母
/// </summary>
/// <param name="str">汉字</param>
/// <returns>首字母</returns>
public static string GetFirstPinyin(string str)
{
string r = string.Empty;
foreach (char obj in str)
{
try
{
ChineseChar chineseChar = new ChineseChar(obj);
string t = chineseChar.Pinyins[0].ToString();
r += t.Substring(0, 1);
}
catch
{
r += obj.ToString();
}
}
return r;
}
}
}