Loren Pechtel
Loren Pechtel

Reputation: 9093

XpsDocumentWriter is leaving a **source** file open

I have a routine that reads XPS documents and chops off pages to separate documents. Originally it read one document, decided how to chop it, closed it and wrote out the new files.

Features were added, this was causing headaches with cleaning up old files before running the routine and so I saved all the chopped pieces to be written out at the end.

ChoppedXPS is a dictionary, the key is the filename, the data is the FixedDocument prepared from the original:

foreach (String OneReport in ChoppedXPS.Keys)
{
    File.Delete(OneReport);
    using (XpsDocument TargetFile = new XpsDocument(OneReport, FileAccess.ReadWrite))
    {
        XpsDocumentWriter Writer = XpsDocument.CreateXpsDocumentWriter(TargetFile);
        Writer.Write(ChoppedXPS[OneReport]);
        Logger($"{OneReport} written to disk", 2);
    }
    Application.DoEvents();
}

If the FixedDocument being written out here contains graphics the source file is opened by the Writer.Write line and left open until the program is closed.

The XpsDocumentWriter does not seem to implement anything that can be used to clean it up.

(Yeah, that Application.DoEvents is ugly--this is an in-house program used by two people, it's not worth the hassle of making this run in the background and without it a big enough task can cause Windows to decide it's non-responsive and kill it. And, yes, I know how to indent--I took them out to make it all fit this screen.)

.Net 4.5, using some C# 8.0 features.

Upvotes: -1

Views: 102

Answers (1)

Loren Pechtel
Loren Pechtel

Reputation: 9093

I found a workaround for this problem. I'm not going to try to post the whole thing as I had to change the whole data handling but the heart of it:

using (XPSDocument Source = new XPSDocument(SourceFile, FileAccess.Read)
{
    [the using loop from my question]
}

I'm still hoping for understanding and something more appropriate than this approach.

Yes--this produces a warning that Source is unused, but the compiler isn't eliminating it so it does work.

Upvotes: 0

Related Questions