1

The following C# code keeps the file locked, so DeleteFile fails:

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 */

Very similar code, which opens the XpsDocument from a file instead of a package doesn't keep the file locked:

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 */

I have seen another post indicating that if you open the document from a file, you need to manually close the underlying package, but that doesn't seem to be the case for me.

I have put a project and the sample file here: https://drive.google.com/open?id=1GTCaxmcQUDpAoPHpsu_sC3_rK3p6Zv5z

Cristi Br
  • 11
  • 2

1 Answers1

0

You are not disposing of the package properly. Wrapping it in a using will most likely resolve the problem:

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);

If that does not resolve the issue, you could look into adding additional FileShare values (specifically FileShare.Delete), however that would only hide the underlying problem rather than fix it.

Jon
  • 3,065
  • 1
  • 19
  • 29
  • I meant to say that I tried disposing the package. That doesn't change the behavior. Also, I don't want to delete the source file. I just want to read it using the package. The solution I have right now is ugly, where if the source is a stream I open using a package, while if the source is a file I have to open the document directly from the file. – Cristi Br Jan 23 '18 at 14:17