加密文件并另存为同一文件

时间:2014-06-23 22:07:27

标签: c#-4.0 encryption

我需要加密我的xml文件并将其保存为同一个文件。 例如:我有一个xml文件test.xml,我需要加密并另存为test.xml。 我使用以下代码:

public static void Encrypt(string inputFilePath, string outputfilePath)
        {
               string EncryptionKey = ConfigurationManager.AppSettings["EncDesKey"];
                var inputFile = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read);

                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 fsOutput = new FileStream(outputfilePath, FileMode.Create))
                    {
                        using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            int data;
                            while ((data = inputFile.ReadByte()) != -1)
                            {
                                cs.WriteByte((byte)data);
                            }
                        }
                    }
                }
        }

但是,我得到的错误是该文件仍被另一个进程使用,我理解。但我无法弄清楚如何实现这一目标。

1 个答案:

答案 0 :(得分:2)

通过使用File.ReadAllBytes(Path)方法,您实际上可以将文件的内容缓存到变量中,然后关闭文件(释放锁定)

试试这个:

public class Encryption
{
    public void Encrypt(string inputFilePath, string outputfilePath)
    {
        string encryptionKey = ConfigurationManager.AppSettings["EncDesKey"];
        var inputData = File.ReadAllBytes(inputFilePath);

        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 fsOutput = new FileStream(outputfilePath, FileMode.Create))
            {
                using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    foreach (var item in inputData)
                    {
                        cs.WriteByte(item);
                    }
                }
            }
        }
    }
}