使用包打开 XPS 文件会使文件保持锁定状态



以下 C# 代码使文件保持锁定状态,因此 DeleteFile 失败:

String srcFile = @"D:IdeletemeTempFilesMemXPS1.xps";
Package package = Package.Open(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read);
XpsDocument xpsDoc = new XpsDocument(package, CompressionOption.Normal, srcFile);
/* Calling this is what actually keeps the file open.
   Commenting out the call to GetFixedDocumentSequence() does not cause lock */
FixedDocumentSequence fds = xpsDoc.GetFixedDocumentSequence();
xpsDoc.Close();
package.Close();
File.Delete(srcFile); /* This will throw an exception because the file is locked */

非常相似的代码,从文件而不是包打开 XpsDocument 不会保持文件锁定状态:

String srcFile = @"D:IdeletemeTempFilesMemXPS1.xps";
XpsDocument xpsDoc = new XpsDocument(srcFile, FileAccess.Read, CompressionOption.Normal);
/* If XpsDocument is opened from file instead of package,
   GetFixedDocumentSequence() doesn't keep the file open */
FixedDocumentSequence fds = xpsDoc.GetFixedDocumentSequence();
xpsDoc.Close();
File.Delete(srcFile); /* This will throw an exception because the file is locked */

我看过另一篇文章,表明如果您从文件打开文档,则需要手动关闭基础包,但对我来说似乎并非如此。

我在这里放了一个项目和示例文件:https://drive.google.com/open?id=1GTCaxmcQUDpAoPHpsu_sC3_rK3p6Zv5z

您没有正确处理包裹。将其包装在using中很可能会解决问题:

String srcFile = @"D:IdeletemeTempFilesMemXPS1.xps";
using(Package package = Package.Open(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
    XpsDocument xpsDoc = new XpsDocument(package, CompressionOption.Normal, srcFile);
    /* Calling this is what actually keeps the file open.
       Commenting out the call to GetFixedDocumentSequence() does not cause lock 
    */
    FixedDocumentSequence fds = xpsDoc.GetFixedDocumentSequence();
    xpsDoc.Close();
    package.Close();
}
File.Delete(srcFile);

如果这不能解决问题,您可以考虑添加其他FileShare值(特别是FileShare.Delete(,但这只会隐藏根本问题而不是修复它。

相关内容

  • 没有找到相关文章

最新更新