Standard way of checking if a file is readable?

c#, file

Solution

Use the `FileSystemInfo.Attributes` property, and check against `FileAttributes.ReadOnly`:

var file = new FileInfo(path);
if ((file.Attributes & FileAttributes.ReadOnly) != 0)
{
    // Do whatever you want for a read-only file
}

Note that that's not the same as whether or not you can write to the file. If it's already in use, then you may well not be able to write to it. Even if it did indicate whether you could write to it at the time you call the property, that wouldn't tell you whether you could write to the file immediately afterwards.

Basically, you have to use a try/catch if you want to handle attempting to write to a file which may fail. I would catch `IOException` specifically (or an even more specific exception, potentially) rather than catching all exceptions though.

Problem

I know you can check if it is read-only, and then do a try-catch statement to see if it is readable, but is there a built in way of checking if a file is already being used?

Original source