在WPF(Windows Presentation Foundation)中加密文件,你可以使用.NET框架提供的加密类。以下是一个基本的步骤,说明如何使用AES加密算法来加密和解密一个文件:
1. 引入命名空间
确保在你的项目中引入了必要的命名空间:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
```
2. 加密文件
下面是一个加密文件的示例方法:
```csharp
public static void EncryptFile(string sourceFilePath, string destinationFilePath, string key, string iv)
{
// 读取源文件
byte[] sourceFileBytes = File.ReadAllBytes(sourceFilePath);
// 创建AES加密对象
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(key);
aesAlg.IV = Encoding.UTF8.GetBytes(iv);
// 创建加密器
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// 创建内存流来保存加密后的数据
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(sourceFileBytes, 0, sourceFileBytes.Length);