使用包打开XPS文件会使文件锁定

时间:2018-01-19 14:16:37

标签: xps filelock

以下C#代码会锁定文件,因此DeleteFile失败:

String srcFile = @"D:\I\deleteme\TempFiles\Mem\XPS\1.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:\I\deleteme\TempFiles\Mem\XPS\1.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

1 个答案:

答案 0 :(得分:0)

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

String srcFile = @"D:\I\deleteme\TempFiles\Mem\XPS\1.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),但这只会隐藏基础问题而不是修复它。