Question

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?

Était-ce utile?

La 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().

Autres conseils

I believe you can simply override the Finalize() method of the class you are using. As per this MSDN article:

The destructor implicitly calls Finalize on the base class of the object. Therefore, the previous destructor code is implicitly translated to the following code:

protected override void Finalize()
{
    try
    {
        // Cleanup statements...
    }
    finally
    {
        base.Finalize();
    }
}

When working in the Finalize() method, you are also assured that no fields have been "collected" yet, and thus you can safely use all of the object's fields.

If your process will crash or be killed, the Dispose() method will not be called. You should test if the certain file is locked by some other process rather than resting if the file exists

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top