Check if the file can be read

This is how I try to check if I can read the file before reading it

FileStream stream = new FileStream(); try { // try to open the file to check if we can access it for read stream = File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read); } catch (IOException ex) { return false; } finally { stream.Dispose(); } 

Is it correct?

Also, File.Open is similar to File.ReadAllText , I mean, are they equally expensive for performance?

+8
c # io file-io
source share
3 answers

If you want to check for exceptions, just add the appropriate try..catch code to Dan Dinu code, for example.

  try { using (FileStream stream = File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read)) { ... // <- Do something with the opened file return true; // <- File has been opened } } catch (IOException) { return false; // <- File failed to open } 
+4
source share

Whether you can read the file depends on a number of factors: do you have permissions, is the hard disk damaged. I would probably go the same way as you.

However, you need to keep in mind that the information you get from this method is just a snapshot. If, right after calling this method, someone changes the file permissions, access to 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 a little more concise:

 try { File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read).Dispose(); return true; } catch (IOException) { return false; } 

Since you are not actually using a stream, you do not need to keep a link to it. Instead, you can immediately get rid of the stream by calling dispose on the result of File.Open() .

EDIT:

See https://gist.github.com/pvginkel/56658191c6bf7dac23b3893fa59a35e8 for an explanation of why I put Dispose() at the end of File.Open() instead of using the using statement.

+3
source share

The solution looks great. You can also use the using statement:

 using (FileStream stream = new FileStream()) { try { stream = File.Open(this.DataSourceFileName, FileMode.Open, FileAccess.Read); } catch { return false; } } 

The compiler translates this into a try / finally block and automatically deletes the object after executing the block code.

File Open only opens a file for reading / writing.

ReadAllText opens the file, reads the text and closes it so that it takes more time; It’s up to you to choose the method that suits your business.

0
source share

All Articles