如何在流返回流时关闭流

  • 本文关键字:返回 c# filestream
  • 更新时间 :
  • 英文 :

 public Stream DecryptFile(string inputFile)//, string outputFile)
    {
        {  
                string password = @"mykey"; // Your 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;
        }
    }

在此代码中,存在流未正确关闭的问题。如果我在返回值之前关闭它,那么它会抛出错误。

应该

执行fsCrypt.Close();,但不应该执行sr.Close();,因为函数的调用方应该能够使用 Stream。

此外,为了在发生错误时正确关闭流,请使用一次性上下文:

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;
}

调用方还应使用此模式:

using (var stream = DecryptFile(string inputFile))
{
    // do something with decrypted file
}
using (FileStream fs = new FileStream(filePath, FileMode.Open,     FileAccess.Read, FileShare.ReadWrite))
{
//code here
}

我认为它是在NET 3.0左右引入的,您不再需要关闭流

使用括号内的所有内容将自动关闭,并在代码离开该部分时被处理掉

使用来实现它可能会好得多。使用关闭并为您处置基础流。

public Stream DecryptFile(string inputFile)//, string outputFile)
{
    string password = @"mykey"; // Your Key Here
    UnicodeEncoding UE = new UnicodeEncoding();
    byte[] key = UE.GetBytes(password);
    using(var fsCrypt = new FileStream(inputFile, FileMode.Open)
    {
        RijndaelManaged RMCrypto = new RijndaelManaged();
        using(CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read))
        {
            StreamReader sr = new StreamReader(cs);
            Stream s = sr.BaseStream;
            return s;
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新