views:

40

answers:

1

Is it possible to create a file using the FileStream object in .net, specifying DeleteAfterClose option and allow read access to that file?

I've tried using:

System.IO.FileStream strBMP = new System.IO.FileStream(sFileName, System.IO.FileMode.Create, System.Security.AccessControl.FileSystemRights., System.IO.FileShare.ReadWrite, 1024, System.IO.FileOptions.DeleteOnClose);

but the other object attempting the read gets a file share violation.

I'm trying to do this because I'm creating the file (a tif), and then using a COM object (MODI) to perform OCR on the image. My problem is that eve after I call the close method on the MODI com object, I still can't delete the file using the System.File.Delete method because the MODI com object hasn't quite finsished with it. I thought if I could create my file with the DeleteAfterClose option, and still allow reading on that file I'd be set, I just can't figure out how to get passed the sharing violation - if it is even possible.

A: 

When two processes are opening the same file, both of them need to specify compatible sets of file sharing flags for the second open to succeed. Unless you can control the flags being passed by MODI when it opens the file, there's probably no way to avoid the sharing violation; for example, if it attempts to open the file in an exclusive mode, it will always fail if your process has the file open, no matter what flags you pass to the FileStream constructor.

A well-designed COM object (which may or may not be the case here) would not leave files open when it was released, so the problem may be related to the .NET COM interop layer; it's possible that it's keeping some MODI COM objects alive in an unanticipated way. Indeed, threads on other forums about this problem all mention managed code. It's possible that some combination of Marshal.FinalReleaseComObject, GC.Collect, and GC.WaitForPendingFinalizers may help solve the problem, but no one appears to have written up a definitive solution (yet) and using those functions feels extremely hacky and very brittle.

Bradley Grainger