In C# Does using File.OpenRead() needs to be closed?

Viewed 2101

I did not find info about https://docs.microsoft.com/en-us/dotnet/api/system.io.file.openread?view=netcore-3.1

I'm checking if the file exists so that it is ready to be used. I will open the file soon later again. And I'm wondering if it is a better practice to close it after making the check.

Do I need to close the file after File.OpenRead()?

bool DoesFileOpensAndRead(string path)
{
    try
    {
        using (File.OpenRead(path))
        {
            return true;
        }
    }
    catch (Exception)
    {
        return false;
    }
}
3 Answers

Since you are using the IDisposable interface through the using statement, you do not need to call Close, Dispose will do that for you.

You do not NEED to close it - it will be closed automatically AT SOME POINT.

BUT: if you actually want to release the file lock that you created without waiting possibly for the next computer restart (or, technically more correct: until someone closes the program and the OS releases the file lock) then yes, you should delete it. This is not a "need" though (same as locking your car in a parking space is not a "need" - you likely get robbed at some point, but you do not need to lock it).

Now, your code example is more funny - it does not work. Period.

Your File.OpenRead is automatically DISPOSED at the end of the function. This is what the using statement does, and using is also internally closing the file. I am just not sure what the sense is as you are not actually doing anything with the file handle. You are WAY better of to not open read but - RTFM.

I'm checking if the file exists so that it is ready to be used.

Ah, yeah. Why not do it with the method that does that?

https://docs.microsoft.com/en-us/dotnet/api/system.io.file.exists?view=netcore-3.1

File.Exists is identical, in particular because "open it soon" is no guarantee that the file

  • is still there when you use it
  • CAN be opened when you use it.

Open does do some additional checks (can you actually read it, from the permissions?), but

  • There is no guarantee that these permissions are in place at he time of test (note how you say "soon," not "immediately"
  • The conditions may change before you open.
Related