0

I'm using a third party library in my .NET Core console application. The library is generating a text file and the library keeps the file locked (possibly a static instance is kept somewhere inside the library) until the process exits.

I need to postprocess the locked file after I have done calling the third-party library functions. Of course, currently I cannot do that because of the infamous "The file is being used by another process" exception (in my case, it's actually the same process).

What would be the easiest and safest approach to gain access to the locked file from the same console application?

Fortunately, I know for sure there will be no parallel threads running and no more other access to this file - once the library is done writing, it is done, although the file remains locked. So, I could safely do whatever I like with the file if only I could "break the lock" or invent some trick to unload that third party library and get the lock released.

JustAMartin
  • 13,165
  • 18
  • 99
  • 183
  • Maybe the FileShare allows you to read as here: https://stackoverflow.com/questions/25097773/system-io-filestream-fileaccess-vs-fileshare – Frank Nielsen Sep 01 '19 at 19:07
  • `FileShare.ReadWrite` got me halfway - I could read the contents but when I tried to write it back I got `Stream is not writable` exception. So, I guess the library has locked the file for writing. – JustAMartin Sep 01 '19 at 19:20
  • Have you closed/disposed all resources from the library? It is not normal to keep a file open, unless the "process" is not completely finished. – Frank Nielsen Sep 01 '19 at 19:24
  • The library documentation asks to initialize it with DI `ServiceCollection`. I tried to make sure that my ServiceCollection instance is null-ified and out of scope when I attempt to write to the file, but still that did not help - most probably, there are some crossreferences. – JustAMartin Sep 01 '19 at 20:14
  • 1
    You could try making your own DI Scope, then do a `myscope.ServiceProvider.RequiredService` and call the "process". Afterwards Dispose the scope. – Frank Nielsen Sep 01 '19 at 20:17
  • Thank you, this approach helped, but only after I added `GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect();` after disposing the scope. I guess, some references were still stuck and only forced GC collection got rid of them and finally closed the file handle. – JustAMartin Sep 01 '19 at 20:33

0 Answers0