【发布时间】:2018-06-28 19:28:26
【问题描述】:
以下 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
【问题讨论】: