C# Word Interop 保存时出现 AccessViolationException
我想编写一个程序,它将读取一大堆 word 97 文件(.doc)并将它们保存为 .docx 文件。我仅限于.Net 2.0。
在这个阶段,我只想让它与我的存根代码一起工作 - 然后我将编写 GUI 和逻辑来在多个位置打开多个文件等...
这是我到目前为止所拥有的:
using MSWord = Microsoft.Office.Interop.Word;
using MSPPoint = Microsoft.Office.Interop.PowerPoint;
然后
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;
据我所知,word文档正在打开。 但是,SaveAs2()
命令似乎抛出 AccessViolationException
并且 .docx 未保存。
有人可以让我知道上面的代码有什么问题,为什么不保存,以及如何修复它吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你被困在 DLL 地狱里了。仅当计算机上安装了 Office 2010 时才使用 SaveAs2()。任何先前的版本确实都会因 AccessViolation 而崩溃,但该方法尚未实现。使用正确的 PIA 版本也可以大大避免此问题,请务必使用您愿意支持的最低版本。
使用 SaveAs() 方法。
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.