由於 Word 檔案為二進位/複合格式,無法直接用 FileStream 讀取純文字。最常見做法是透過 Microsoft.Office.Interop.Word COM 元件自動化 Word 應用程式開啟文件、全選、複製到剪貼簿、再取出純文字。
using Word = Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
using System.Windows.Forms; // Clipboard, DataFormats
public string ReadWordText(string filePath)
{
Word.Application app = null;
Word.Document doc = null;
try
{
app = new Word.Application { Visible = false };
object file = filePath;
object missing = Type.Missing;
doc = app.Documents.Open(ref file, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Text))
return data.GetData(DataFormats.Text).ToString();
return string.Empty;
}
finally
{
if (doc != null)
{
object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
doc.Close(ref saveChanges);
}
if (app != null)
app.Quit();
// 釋放 COM 物件
if (doc != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
if (app != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
GC.Collect(); GC.WaitForPendingFinalizers();
}
}
AutomationSecurity 或使用無訊息模式。桌面應用程式、低頻率讀取、需完整排版還原時使用 COM 互操作;伺服器端、高效能、批次處理請改用 Open XML SDK 或 NPOI。