c# - How to close a stream when it returns a stream -


 public stream decryptfile(string inputfile)//, string outputfile)     {         {                   string password = @"mykey"; // key here                  unicodeencoding ue = new unicodeencoding();                 byte[] key = ue.getbytes(password);                  filestream fscrypt = new filestream(inputfile, filemode.open);                  rijndaelmanaged rmcrypto = new rijndaelmanaged();                  cryptostream cs = new cryptostream(fscrypt,                     rmcrypto.createdecryptor(key, key),                     cryptostreammode.read);                   streamreader sr = new streamreader(cs);                  stream s = sr.basestream;                 //sr.close();                 //fscrypt.close();              return s;         }     } 

in code there problem stream not closing properly. if close before returning value throws error.

fscrypt.close(); should performed, sr.close(); should not performed, since caller of function should able use stream.

also, in order close streams when errors occur, use disposable context:

using (filestream fscrypt = new filestream(inputfile, filemode.open)) {     rijndaelmanaged rmcrypto = new rijndaelmanaged();      cryptostream cs = new cryptostream(fscrypt,         rmcrypto.createdecryptor(key, key),         cryptostreammode.read);      streamreader sr = new streamreader(cs);     stream s = sr.basestream;     return s; } 

the caller should use pattern:

using (var stream = decryptfile(string inputfile)) {     // decrypted file } 

Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -