7
votes

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.

3
The program itself runs without errors. If I try opening the resulting file, it merely yields 'Word experienced an error trying to open the file'. When I try to look at it with Open XML SDK 2.0 Productivity Tool, it reports 'File contains corrupted data'.GregA
can u please upload an example of the rtf which gives error?Ahmed Magdy

3 Answers

4
votes

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();
2
votes

Can you show the code where you are calling SaveAs? I am curious which Word.WdSaveFormat you are specifying. It sounds like it is saving the rtf data, but changing the extension to .docx.

2
votes

Here is the code that does conversion. The code is almost the same as shown above, with some small (but important) difference - it is necessary to use references (not objects themselves):

Microsoft.Office.Interop.Word.Application _App = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document _Doc =  _App.Documents.Open("c:/xxx.rtf");

object _DocxFileName = "C:/xxx.docx";
Object FileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatXMLDocument;

_Doc.SaveAs2(ref _DocxFileName, ref FileFormat);