2014-06-24 74 views
0

嘗試反序列化爲XML時出現「無法訪問已關閉的文件」錯誤。 我有一個加密的文件。我解密文件並嘗試反序列化它,當我得到這個錯誤。 它工作正常,沒有加密和解密。無法訪問已關閉的文件錯誤

XmlSerializer xmlSerializer = new XmlSerializer(typeof(Models.Test)); 
var fileLocStream = FileManipultions.DecryptToStream(fileLoc); 
var testResult = (Models.Test)xmlSerializer.Deserialize(FileManipultions.DecryptToStream(fileLoc)); 


public static Stream DecryptToStream(string inputFilePath) 
     { 
      try 
      { 
       string EncryptionKey = ConfigurationManager.AppSettings["EncDesKey"].ToString(); 
       CryptoStream cs; 
       using (Aes encryptor = Aes.Create()) 
       { 
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); 
        encryptor.Key = pdb.GetBytes(32); 
        encryptor.IV = pdb.GetBytes(16); 

        using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open)) 
        { 
         cs = new CryptoStream(fsInput, encryptor.CreateDecryptor(), CryptoStreamMode.Read); 
        } 
       } 
       return cs; 
      } 
      catch (Exception ex) 
      { 
       Logger.LogException(ex.Message, System.Reflection.MethodBase.GetCurrentMethod().ToString()); 
       return null; 
      } 
     } 

回答

2

您在方法退出之前關閉fsInput(因此cs)。當方法的調用者獲得流的時候,它就被關閉了。將您的代碼使用using內的cs流進行FileStream。

或者,去掉DecryptToStream()中的所有使用語句,並讓您的類實現IDisposable,以便在使用Stream時完成清理。

相關問題