title: How to properly handle exceptions when performing file io
body: <p>Often I find myself interacting with files in some way but after writing the code I'm always uncertain how robust it actually is. The problem is that I'm not entirely sure how file related operations can fail and, therefore, the best way to handle exceptions.</p>
  <p>The simple solution would seem to be just to catch any <code>IOExceptions</code> thrown by the code and give the user an &quot;Inaccessible file&quot; error message, but is it possible to get a bit more fine-grained error messages? Is there a way to determine the difference between such errors as a file being locked by another program and the data being unreadable due to a hardware error?</p>
  <p>Given the following C# code, how would you handle errors in a user friendly (as informative as possible) way?</p>
  <pre><code>public class IO
  {
     public List&lt;string&gt; ReadFile(string path)
     {
        FileInfo file = new FileInfo(path);
  
        if (!file.Exists)
        {
           throw new FileNotFoundException();
        }
  
        StreamReader reader = file.OpenText();
        List&lt;string&gt; text = new List&lt;string&gt;();
  
        while (!reader.EndOfStream)
        {
           text.Add(reader.ReadLine());
        }
  
        reader.Close();
        reader.Dispose();
        return text;
     }
  
     public void WriteFile(List&lt;string&gt; text, string path)
     {
        FileInfo file = new FileInfo(path);
  
        if (!file.Exists)
        {
           throw new FileNotFoundException();
        }
  
        StreamWriter writer = file.CreateText();
  
        foreach(string line in text)
        {
           writer.WriteLine(line);
        }
  
        writer.Flush();
        writer.Close();
        writer.Dispose();
     }
  }
  </code></pre>