0

I need to read from a number of files but sometimes they are not available or cannot be read from current user. This is the code I'm using to check if file is valid but I think I'm not using the using statement correctly.

private static bool fileAccessible(string filePath) {
    using (FileStream fs = new FileStream(filePath, FileMode.Open)) {
        if (fs.CanRead) {
            return true;
        }
        else {
            return false;
        }
    }

    return false; // compiler says "unreachable code"
}

Should I insert a try/catch block outside the using statement to catch errors raised by unavailable file or will using go on without raising an error if filePath is not available?

Bonus question: is this the correct way to check if file is available and accessible? If the answer is Yes can I change FileMode.Open to FileMode.Append to perform the same check on writable files?

Naigel
  • 9,086
  • 16
  • 65
  • 106
  • return false; // compiler says "unreachable code" is not needed. – Dreamweaver May 13 '15 at 07:47
  • the duplicate question addresses only permission issue, but I need also to check if file exists – Naigel May 13 '15 at 07:48
  • @Naigel you can call `File.Exists(filepath)` to check files exists before using statement – Jeffrey Zhang May 13 '15 at 07:49
  • 1
    The file system isn't solely under the control of your program. As such, this function might return `true` but by the time you actually take action based on this, the file may no longer be available. As such, I'd say that this is mostly a waste of time - just go ahead and try to *use* the file in whatever way you're going to and react to failures when they happen. – Damien_The_Unbeliever May 13 '15 at 08:03
  • @Damien_The_Unbeliever do you think this approach should be used every time I interact with file? For example I need to write to some files, should I always use a pattern like `try { using (StreamWriter file = ... { file.Write("xxx") } }` ? – Naigel May 13 '15 at 08:45
  • 1
    Yes, to an extent. For any resources outside of the control of your application (the file system, the network, remote servers) you *have* to write code that can cope with failures occurring at any time. No amount of up-front testing can answer the question "will I be able to complete task X?" Whether you choose to do this with a local exception handler immediately wrapped around each access or take a more global view is up to you. – Damien_The_Unbeliever May 13 '15 at 09:00

1 Answers1

0

Yes, it always better to use try catch as IO exception can occur due to some connectivity issue or file not found exception can occur.

   private static bool fileAccessible(string filePath) {
            return  File.Exists(filePath);

    }
Dreamweaver
  • 1,328
  • 11
  • 21