Can anybody tell me how to remove all CA2202 warnings from the following code?
public static byte[] Encrypt(string data, byte[] key, byte[] iv)
{
us
I wanted to solve this the right way - that is without suppressing the warnings and rightly disposing all disposable objects.
I pulled out 2 of the 3 streams as fields and disposed them in the Dispose()
method of my class. Yes, implementing the IDisposable
interface might not necessarily be what you are looking for but the solution looks pretty clean as compared to dispose()
calls from all random places in the code.
public class SomeEncryption : IDisposable
{
private MemoryStream memoryStream;
private CryptoStream cryptoStream;
public static byte[] Encrypt(string data, byte[] key, byte[] iv)
{
// Do something
this.memoryStream = new MemoryStream();
this.cryptoStream = new CryptoStream(this.memoryStream, encryptor, CryptoStreamMode.Write);
using (var streamWriter = new StreamWriter(this.cryptoStream))
{
streamWriter.Write(plaintext);
}
return memoryStream.ToArray();
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.memoryStream != null)
{
this.memoryStream.Dispose();
}
if (this.cryptoStream != null)
{
this.cryptoStream.Dispose();
}
}
}
}