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.
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();
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With