在我的应用程序中,我想读取文档文件(.doc或.odt或.docx)并将该文本存储在字符串中。为此,我使用以下代码:
string text;
using (var streamReader = new StreamReader(@"D:\Sample\Demo.docx", System.Text.Encoding.UTF8))
{
text = streamReader.ReadToEnd();
}
但我无法阅读或复制正确的文字,因为它显示如下:
PK ! x% E [Content_Types].xml ( IO0HWp @ 5rJqvIj /ۿ克%j)的P.ytfN&QY 0 T9 w, L!jk gs @ л 0! Bp Y VJ t + N Kk Z'(Y / IX | / FL骐^ w ^ $¹ZIho|?btŔr+ W6V7 *宽$}ëDΧriq= , Fݜ t 5+ Z( ? a z i [!0 k ,}O Ta \ m? i | ж AT SB ;'m; y \9 “La o % @k8 ?,Fc hL_\ 9I ! = m TT |P ̩}} $ | = | } PK
如何从文档文件中读取或复制文本?
为此,您需要使用不同的库
使用Microsoft.Office.Interop.Word
从Word文档读取数据的示例
using System;
using Microsoft.Office.Interop.Word;
class Program
{
static void Main()
{
// Open a doc file.
Application application = new Application();
Document document = application.Documents.Open("C:\\word.doc");
// Loop through all words in the document.
int count = document.Words.Count;
for (int i = 1; i <= count; i++)
{
// Write the word.
string text = document.Words[i].Text;
Console.WriteLine("Word {0} = {1}", i, text);
}
// Close word.
application.Quit();
}
}
Microsoft DocX格式是一个容器,并不保存简单明文(您的StreamReader
尝试阅读的数据)。
您应该考虑使用如下的第三方库:https://docx.codeplex.com/