using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Office.Interop.Word;
public class ChineseStrConverter : IDisposable
{
private Application wordApp = null;
private Document doc = null;
public ChineseStrConverter()
{
wordApp = new Application();
wordApp.Visible = false;
doc = wordApp.Documents.Add();
}
public string ConvChineseString(string src, bool chs2cht = false)
{
string result = null;
try
{
doc.Content.Text = src;
doc.Content.TCSCConverter(
chs2cht ? //由參數決定簡->繁或是繁->簡
WdTCSCConverterDirection.wdTCSCConverterDirectionSCTC :
WdTCSCConverterDirection.wdTCSCConverterDirectionTCSC,
true, true);
//取回轉換結果時,結尾會多出\r
result = doc.Content.Text.TrimEnd('\r');
}
catch (Exception ex)
{
result = "Error: " + ex.Message;
}
return result;
}
public void Dispose()
{
//確實關閉Word Application
try
{
//關閉Word檔
object dontSave = WdSaveOptions.wdDoNotSaveChanges;
((_Document)doc).Close(ref dontSave);
//確保Document COM+釋放
if (doc != null)
Marshal.FinalReleaseComObject(doc);
doc = null;
((_Application)wordApp).Quit(ref dontSave);
}
finally
{
Marshal.FinalReleaseComObject(wordApp);
}
}
}