title: How do you check for permissions to write to a directory or file?
body: <p>I got a program that writes some data to a file using a method like the one below.</p>
  
  <pre><code>
  public void ExportToFile(string filename)
  {
       using(FileStream fstream = new FileStream(filename,FileMode.Create))
       using (TextWriter writer = new StreamWriter(fstream))
       {
           // try catch block for write permissions 
           writer.WriteLine(text);
  
  
       }
  }
  </code></pre>
  
  <p>When running the program I get an error:</p>
  
  <blockquote>
    <p>Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'mypath' is denied.
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access,
    nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions
    ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
       at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access
    FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolea
    bFromProxy)</p>
  </blockquote>
  
  <p>Question: What code do I need to catch this and how do I grant the access?</p>