title: What are the best practices for file handling in c#?
body: <p>I have a couple questions on how to do file handling properly. I use binary serialization and deserialization in my program. On top of that I also export and import text files. I listed a example below of my serialization code.
  I use an openfile dialog to select folders/files.</p>
  
  <p>This is my binary serialization method:</p>
  
  <pre><code>if (string.IsNullOrWhiteSpace(fileName))
  {
      throw new ArgumentOutOfRangeException("fileName");
  }
  
  FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate);
  
  try
  {
      BinaryFormatter binaryFormatter = new BinaryFormatter();
      binaryFormatter.Serialize(fileStream, Animals);
  }
  finally
  {
      fileStream.Close();
  }
  </code></pre>
  
  <p>And these are the exceptions i catch:</p>
  
  <pre><code>try
  {
      administration.Load(fileName);
  }
  catch (NotSupportedException nonSupportedException)
  {
      MessageBox.Show(nonSupportedException.Message);
  }
  catch (UnauthorizedAccessException unauthorizedAccesException)
  {
      MessageBox.Show(unauthorizedAccesException.Message);
  {
  catch (SecurityException securityException)
  {
      MessageBox.Show(securityException.Message);
  }
  catch (DirectoryNotFoundException directoryNotFoundException)
  {
      MessageBox.Show(directoryNotFoundException.Message);
  }
  catch (IOException IOException)
  {
      MessageBox.Show(IOException.Message);
  }
  </code></pre>
  
  <p>I catch the same exceptions for deserialization. The only difference there is these 3 lines:</p>
  
  <pre><code>if (File.Exists(fileName)) { }
  FileStream fileStream = new FileStream(fileName, FileMode.Open);
  Animals = formatter.Deserialize(fileStream) as List&lt;Animal&gt;;
  </code></pre>
  
  <p>What should I do if I get wrong data? For example: half of the file has the right data and the other half doesn't. </p>
  
  <p>How should i write unit tests for serialization? Many exceptions like SecurityException are hard to test.</p>
  
  <p>What exceptions should I catch? I looked at MSDN, but I am not sure if I should just straight up catch all of the exceptions listed. I deliberately don't catch the ArgumentOutOfRange exception for example, because I don't want to catch programming mistakes.</p>
  
  <p>I have the same questions for reading and writing text files. Is there a difference in testing/exception catching? The only difference is that I use StreamWriter for writing text files. And I use File.ReadAllLines to read the text file I select.</p>
  
  <p>Thank you.</p>