Problems With XMLWriter and Cryptostreams

  • Thread starter Thread starter Will
  • Start date Start date
W

Will

I'm having problems with the following code:

public static void saveEncryptedSession(DataSet ds, string pathToSave)
{
const string encryptionKey = "base64-string-snipped";
byte[] myKey = Convert.FromBase64String(encryptionKey);
XmlTextWriter w = new XmlTextWriter(pathToSave, Encoding.UTF8);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(w.BaseStream,RMCrypto.CreateEncryptor(myKey, myKey), CryptoStreamMode.Write);

ds.WriteXml(cs);

cs.Close();
w.Close(); -- errors out here: System.ObjectDisposedException Occured in
mscorlib.dll

}

Additional Information: Cannot Access a Closed File

Wondering if anyone has any insight on this? To give a little context I'm
basing my code off:
http://www.dotnet247.com/247reference/msgs/20/100432.aspx

Any Help would be appreciated, Thanks.
 
Will said:
I'm having problems with the following code:

public static void saveEncryptedSession(DataSet ds, string pathToSave)
{
const string encryptionKey = "base64-string-snipped";
byte[] myKey = Convert.FromBase64String(encryptionKey);
XmlTextWriter w = new XmlTextWriter(pathToSave, Encoding.UTF8);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(w.BaseStream,
RMCrypto.CreateEncryptor(myKey, myKey), CryptoStreamMode.Write);

ds.WriteXml(cs);

cs.Close();
w.Close(); -- errors out here: System.ObjectDisposedException Occured in
mscorlib.dll

}

Additional Information: Cannot Access a Closed File

Wondering if anyone has any insight on this? To give a little context I'm
basing my code off:
http://www.dotnet247.com/247reference/msgs/20/100432.aspx

Any Help would be appreciated, Thanks.

You don't need to close the writer after closing the crypto stream -
that will close it for you.

I'd suggest using using blocks instead though - unfortunately you still
need to call cs.FlushFinalBlock, but the closing logic will be much
more robust. (If an exception occurs during your code, you're currently
not closing the file.)

Looking at your code though, I can't see why you're using an
XmlTextWriter anyway - you're only using the BaseStream property of it,
so why not just create a FileStream to start with? That would make the
code clearer, IMO.
 
Back
Top