6

I want to write a program which will read in a whole bunch of word 97 files (.doc) and save them as .docx files. I'm restricted to .Net 2.0.

At this stage, I just want to get it working with my stub code - then I will write the GUI and logic to open multiple files in multiple locations, etc...

Here's what I have so far:

using MSWord   = Microsoft.Office.Interop.Word;
using MSPPoint = Microsoft.Office.Interop.PowerPoint;

then

OpenFileDialog ofd = new OpenFileDialog()
{
  CheckFileExists = true,
};

if (ofd.ShowDialog() != DialogResult.OK)
  return;

MSWord.Application app = new MSWord.Application();
MSWord.Document    doc = new MSWord.Document();

doc = app.Documents.Open(ofd.FileName);

try
{
  doc.SaveAs2(ofd.FileName + ".docx", MSWord.WdSaveFormat.wdFormatDocument);
}
catch (Exception ex)
{
  MessageBox.Show("Could not save because:\r\n" + ex.Message,
    ex.GetType().ToString());
}

doc.Close();
app.Quit();

return;

As far as I can tell, the word document is being opened. However, the SaveAs2() command seems to throw an AccessViolationException and the .docx is not saved.

Can someone please let me know what is wrong with the above code, why it's not saving, and how to fix it?

Thanks

Ozzah
  • 10,631
  • 16
  • 77
  • 116

1 Answers1

11

You are stuck in DLL Hell. Only use SaveAs2() when you have Office 2010 installed on the machine. Any prior version is indeed going to bomb with an AccessViolation, the method isn't implemented. Using the proper PIA version would go a long way as well to avoid this problem, be sure to use the lowest version you are willing to support.

Use the SaveAs() method.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Thanks Hans. `SaveAs()` isn't available in version 14 of the interop library, but is available in version 12. Oddly, it is available in version 14 of the PowerPoint interop. I've since fixed it with `SaveAs()` as you suggested and it works great. :) – Ozzah Apr 04 '11 at 02:41