Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you do it like this, it should work:</p> <pre><code>// A: encrypting when writing // 1. create backing storage stream. In your case a file stream using(Stream innerStream = File.Create(path)) // 2. create a CryptoStream in write mode using(Stream cryptoStream = new CryptoStream(innerStream, encryptor, CryptoStreamMode.Write)) { // 3. write to the cryptoStream binaryFormatter.Serialize(cryptoStream, obj); } // B: decrypting when reading // 1. create backing storage stream. In your case a file stream using(Stream innerStream = File.Open(path, FileMode.Open)) // 2. create a CryptoStream in read mode using(Stream cryptoStream = new CryptoStream(innerStream, decryptor, CryptoStreamMode.Read)) { // 3. read from the cryptoStream obj = binaryFormatter.Deserialize(cryptoStream); } </code></pre> <p>There are a couple of problems with your code:</p> <ol> <li><p>You're using an encryptor when reading. This was probably a typo, but it should be a decryptor.</p></li> <li><p>You are flushing the <code>buffer</code>, but that is not enough when using a <code>CryptoStream</code>. Encryptors and decryptors work on blocks of a fixed size. The last block may not have that size, so it needs special treatment. The last block is the one written before the stream is <em>closed</em>, not <em>flushed</em>. Flushing on a CryptoStream does nothing useful, because it cannot write anything of size less than the input block size of the encryptor/decryptor, unless it is the last thing to be written. And on top of this, in general you should always close your streams, no matter what. The <code>using</code> statement is the recommended way of doing it:</p> <pre><code>using(buffer) _binaryFormatter.Serialize(buffer, bObj); </code></pre></li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload