Search code examples
c#.netfiledestructormanaged

Is there a safe way to use a managed field in destructor?


I have a class that creates a hidden file in the constructor and keeps its FileStream open until Dispose() is called. Calling Dispose() closes the stream and removes the hidden file.

I need to make sure that the file is removed if the program is closed without a call to Dispose(). I thought I can check if it still exists and call File.Delete(path) if it does in the destructor but the string field that holds the file path can already be collected when the destructor is called, right?

Is there a safe way to access that field from destructor?
If not, is there another way for me to make sure that file is deleted?


Solution

  • but the string field that holds the file path can already be collected when the destructor is called, right?

    No. That string will still be there and safe to use.

    But you'll have to maneuver carefully, closing your file first if it's still open.

    I need to make sure that the file is removed if the program is closed without a call to Dispose()

    That's the big challenge. Not much guarantees here. Make sure the client code always calls Dispose().