Search code examples
c#.netms-wordrtfoffice-interop

Invoking Word for rtf to docx conversion


I have a need to routinely programmatically convert *.rtf files into *.docx. Manually, this works just fine with Save As inside Word 2007 ... the resulting docx behaves just fine. Programmatically, I can't get it to work.

What I tried is basically the following:

Fetch RTF from Word

... but in the reverse direction. Instead of opening *.docx and using SaveAs to *.rtf, I'm opening the *.rtf and using SaveAs to *.docx. However, the resulting file won't open, and so evidently there's something I don't understand. Is

wordApp.Documents.Open(@"D:\Bar\foo.rtf")

not a legit thing to do?

Any thoughts about how to do this would be appreciated.


Solution

  • You can try this code, it works for me

    var wordApp = new Microsoft.Office.Interop.Word.Application();
    var currentDoc = wordApp.Documents.Open(@"C:\TestDocument.rtf");
    currentDoc.SaveAs(@"C:\TestDocument.doc", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument97);
    

    I got the same error when I tried to use wdFormatDocument or wdFormatDocumentDefault

    EDIT: this is an update to the code, it converts it but u will get the error once then it never appeared again!!

    var wordApp = new Microsoft.Office.Interop.Word.Application();
    var currentDoc = wordApp.Documents.Open(@"C:\TestDocument.rtf");
    currentDoc.SaveAs(@"C:\TestDocument", Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocumentDefault);
    currentDoc.Close();
    wordApp.Quit();