0

When i try to save a file with docx extension in winform C# and to open that i get exception:
"word cannot open the file because the file format does not match the file extension"

This is how i save the file:

object oMissing = Missing.Value;
Word.Application oWord = new Word.Application();
Word.Document oWordDoc = new Word.Document();
oWord.Visible = false;
oWordDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);  

Object oSaveAsFile = (Object)@"C:\test\FINISHED_XML_Template.docx";            
        oWordDoc.SaveAs(ref oSaveAsFile, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing);

        oWordDoc.Close(false, ref oMissing, ref oMissing);
        oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
Nissim
  • 31
  • 1
  • 5

2 Answers2

0

This page suggests changing to using the Word.Application.SaveAs2() method.

http://social.msdn.microsoft.com/Forums/en-US/0d7a68c0-e2cd-41c0-9815-63f0fde0bc8d/converting-doc-to-docx?forum=worddev

Martin Costello
  • 9,672
  • 5
  • 60
  • 72
0

See the answer in this link: Convert .doc to .docx using C#

Daves solution is like the below, but I have changed Daves code from CompatibilityMode:=WdCompatibilityMode.wdWord2010 to CompatibilityMode:=WdCompatibilityMode.wdWord2013 to be more up-to-date and to give you true docx (without compability mode).

public void ConvertDocToDocx(string path)
{
    Application word = new Application();

    if (path.ToLower().EndsWith(".doc"))
    {
        var sourceFile = new FileInfo(path);
        var document = word.Documents.Open(sourceFile.FullName);

        string newFileName = sourceFile.FullName.Replace(".doc", ".docx");
        document.SaveAs2(newFileName,WdSaveFormat.wdFormatXMLDocument, 
                         CompatibilityMode: WdCompatibilityMode.wdWord2013);

        word.ActiveDocument.Close();
        word.Quit();

        File.Delete(path);
    }
}