C# 4.0 加密文件并另存为同一文件
我需要加密我的xml文件并将其另存为同一个文件。 例如:我有一个xml文件test.xml,需要对其进行加密并另存为test.xml。 我使用以下代码:C# 4.0 加密文件并另存为同一文件,c#-4.0,encryption,C# 4.0,Encryption,我需要加密我的xml文件并将其另存为同一个文件。 例如:我有一个xml文件test.xml,需要对其进行加密并另存为test.xml。 我使用以下代码: public static void Encrypt(string inputFilePath, string outputfilePath) { string EncryptionKey = ConfigurationManager.AppSettings["EncDesKey"];
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);
}
}
}
}
}
但是,我得到的错误是,该文件仍被另一个进程使用,我理解这一点。但是我还没有弄明白如何实现这一点。通过使用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);
}
}
}
}
}
}
您可以使用临时中间文件或数组。不是一个理想的解决方案,但一切都应该正常。是的,我试图避免使用临时文件。