简体   繁体   中英

C# Word Interop AccessViolationException when saving

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM