Whether a file can be read depends on a number of factors: do you have permissions, whether the hard disk is broken. I would probably have gone the same route as you did.
However, you do have to keep in mind that the information you get from this method is just a snapshot. If immediately after you call this method, someone changes the permissions on the file, accessing the file later in your code will still fail. You should not depend on the result of this method.
Just a suggestion, the following code does the same but is a bit more concise:
try
{
File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read).Dispose();
return true;
}
catch (IOException)
{
return false;
}
Since you're not really using the stream, you don't have to hold on a reference to it. Instead, you can just immediately dispose of the stream by calling dispose on the result of File.Open()
.
EDIT:
See https://gist.github.com/pvginkel/56658191c6bf7dac23b3893fa59a35e8 for an explanation on why I've put the Dispose()
at the end of the File.Open()
instead of using the using
statement.