我提出了一种稍微不同的方法来保存Word.Document
文件,使用内部Document.SaveAs2方法,使用编码文本作为输出格式。
这允许您使用Microsoft Office Unicode 编码,它应该涵盖所有可能的语言编码。
它还允许您指定应如何处理双向标记。如果此选项设置为true
,则保留双向原始设置。
Microsoft.Office.Interop.Word.Application WordApplication = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document DefaultDocument;
DefaultDocument = WordApplication.Documents.Open(FilePath);
CultureInfo culture = new CultureInfo((int)DefaultDocument.Content.LanguageID);
string SaveFileName = Path.Combine(Path.GetDirectoryName(FilePath),
Path.GetFileNameWithoutExtension(FilePath));
DefaultDocument.SaveAs2(SaveFileName, WdSaveFormat.wdFormatEncodedText, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing,
MsoEncoding.msoEncodingUnicodeLittleEndian, Type.Missing, Type.Missing,
Type.Missing, true); //<- BiDi Marks
//Release the Document
foreach (Document WDocument in WordApplication.Documents)
{
WDocument.Close(WdSaveOptions.wdDoNotSaveChanges);
Marshal.ReleaseComObject(WDocument);
}
//Release the WINWORD Process
WordApplication.Quit(WdSaveOptions.wdDoNotSaveChanges);
Marshal.ReleaseComObject(WordApplication);
Marshal.CleanupUnusedObjectsInCurrentContext();
//Test the results using a RichTextBox
richTextBox1.RightToLeft = (culture.TextInfo.IsRightToLeft) ? RightToLeft.Yes : RightToLeft.No;
richTextBox1.ImeMode = ImeMode.On;
richTextBox1.Text = File.ReadAllText(SaveFileName + ".txt");
这是 RichTextBox 控件中显示的结果。

作为 的替代方法,您可以从Document.LanguageID数值Document.SaveAs2
派生编码,该数值引用文化标识符 (LCID)。
(在前面的代码中已经定义了)CultureInfo
culture
Encoding encoding = (culture.TextInfo.IsRightToLeft)
? Encoding.GetEncoding(culture.TextInfo.ANSICodePage)
: Encoding.Unicode;
using (MemoryStream MemStream = new MemoryStream(encoding.GetBytes(DefaultDocument.Content.Text)))
using (StreamReader reader = new StreamReader(MemStream, encoding))
File.WriteAllText(SaveFileName + ".txt", reader.ReadToEnd());