13

When I am trying to read .doc file using DocumentFormat.OpenXml dll its giving error as "File contains corrupted data."

This dll is reading .docx file properly.

Can DocumentFormat.OpenXml dll help in reading .doc file?

string path = @"D:\Data\Test.doc";
string searchKeyWord = @"java";

private bool SearchWordIsMatched(string path, string searchKeyWord)
{
    try
    {
       using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(path, true))
       {
           var text = wordDoc.MainDocumentPart.Document.InnerText;
           if (text.Contains(searchKeyWord))
               return true;
           else
               return false;
       }
     }
     catch (Exception ex)
     {
         throw ex;
     }
}
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Shardaprasad Soni
  • 541
  • 2
  • 6
  • 10

4 Answers4

18

The old .doc files have a completely different format from the new .docx files. So, no, you can't use the OpenXml library to read .doc files.

To do that, you would either need to manually convert the files first, or you would need to use Office interop, instead of the Open XML SDK you're using now.

svick
  • 236,525
  • 50
  • 385
  • 514
6

I'm afraid there won't be any better answer than the ones already given. The Microsoft Word DOC format is binary whereas OpenXML formats such as DOCX are zipped XML files. The OpenXml framework is for working with the latter only.

As suggested, the only other option you have is to use Word interop or third party library to convert DOC -> DOCX which you can then work with the OpenXml library.

Adam
  • 2,762
  • 1
  • 30
  • 32
3

.doc (If created with an older version of Microsoft Word) does not have the same structure as a .docx (Which is basically a zip file with some XML documents).

If your .doc is 'unzippable' (Just rename the .doc extension to .zip) to probe, you'll have to manually convert the .doc to a .docx.

Alex
  • 7,901
  • 1
  • 41
  • 56
0

You can use IFilterTextReader.

TextReader reader = new FilterReader(path);
using (reader)
{
    txt = reader.ReadToEnd();
}

You can take a look at http://www.codeproject.com/Articles/13391/Using-IFilter-in-C

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
  • This looks promising. Can you provide a link to the project as well? And perhaps an explanation as to why this works? – Nate Barbettini Oct 22 '15 at 22:41
  • Sorry, my english is not that good... but you could take a look at this: http://www.codeproject.com/Articles/13391/Using-IFilter-in-C – Indaiá Melo Oct 22 '15 at 22:50