title: C# Encrypting and Decrypting a text file
body: <p>I'm trying to encrypt and then decrypt a file when needed, and read the file for use of the program. Still learning cryptography and I looked at several examples and tried this.</p>
  <p>I have managed to en- and decrypt string but sadly that did not work in this case.</p>
  <p>Cryptostream gives an IV does not match block size error on encrypt. Could not even have tested decrypting but that is most likely off too.</p>
  <p>So question is: <strong>How can I encrypt, decrypt and read a .txt file?</strong></p>
  <pre><code>private void EncryptFile(string resultFile)
      {
          string password = @&quot;test&quot;; 
  
          UnicodeEncoding UE = new UnicodeEncoding();
          byte[] key = UE.GetBytes(password);
  
          FileStream fsCrypt = File.Create(resultFile);
  
          RijndaelManaged rmCrypto = new RijndaelManaged();
  
          CryptoStream cs = new CryptoStream(fsCrypt, rmCrypto.CreateEncryptor(key, key),CryptoStreamMode.Write);
  
          StreamWriter sWriter = new StreamWriter(cs);
  
          sWriter.WriteLine(resultFile);
  
          sWriter.Close();
          cs.Close();
          fsCrypt.Close();
      }
  
      private void DecryptFile(string resultFile)
      {
  
          string password = @&quot;test&quot;;
  
          UnicodeEncoding UE = new UnicodeEncoding();
          byte[] key = UE.GetBytes(password);
  
          FileStream fsCrypt = new FileStream(resultFile, FileMode.Open);
  
          RijndaelManaged rmCrypto = new RijndaelManaged();
  
          CryptoStream cs = new CryptoStream(fsCrypt, rmCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read);
  
          StreamWriter sWriter = new StreamWriter(cs);
  
          sWriter.WriteLine(resultFile);
  
          sWriter.Close();
          cs.Close();
          fsCrypt.Close();
      }
  </code></pre>