打开 XML SDK:“进程无法访问文件 'x',因为它正被另一个进程使用。”

Open XML SDK: 'The process cannot access the file 'x' because it is being used by another process.'

这是我修改 PowerPoint 演示文稿的代码,将其另存为新文件,关闭它,然后尝试打开该文件。

var doc = PresentationDocument.Open(@"d:\temp.pptx", true);    
//... proccess presentation
doc.SaveAs(@"d:\temp2.pptx");
doc.Close();

var doc2 = PresentationDocument.Open(@"d:\temp2.pptx", false);
doc2.Close();

我无法理解为什么运行-时间抛出异常:

The process cannot access the file 'x' because it is being used by another process.

您必须使用 using 语句打开您的演示文稿。大致如下:

using (var doc = PresentationDocument.Open(@"d:\temp.pptx", true))
{    
//... proccess presentation
doc.SaveAs(@"d:\temp2.pptx");
doc.Close(); //may be unnecessary
}

我注意到 doc.SaveAs() return 对象,我刚刚关闭了它

var savedDoc = doc.SaveAs(@"d:\temp2.pptx") as PresentationDocument;

savedDoc.Close();