C# 多文件加密压缩与解压还原
1、多文件加密压缩
public class PackageEntity { public string PatchName { get; set; } public string PatchUrl { get; set; } public string FullPath { get; set; } }
public List<PackageEntity>GetAllFiles(string filePath) { var list = new List<PackageEntity>(); DirectoryInfo dir = new DirectoryInfo(@"C"); var dirInfo = dir.GetDirectories(); var filesInfo = dir.GetFiles(); foreach (var item in filesInfo) { list.Add(new PackageEntity { PatchName = item.Name, PatchUrl = item.FullName, FullPath = item.FullName }); } return list; }
//计算总条数 byte[] fileCountBytes = Encoding.UTF8.GetBytes(list.Count.ToString()); byte[] countSizeBytes = BitConverter.GetBytes(fileCountBytes.Length); ms.Write(countSizeBytes, 0, countSizeBytes.Length); ms.Write(fileCountBytes, 0, fileCountBytes.Length); foreach (var item in list) { if (!File.Exists(item.FullPath)) continue; byte[] fileNameBytes = Encoding.UTF8.GetBytes(item.PathUrl); //rsa加密 fileNameBytes = RSAHelper.RsaEncrpyt(fileNameBytes, key); byte[]sizeBytes = BitConverter.GetBytes(fileNameBytes.Length); ms.Write(sizeBytes, 0, sizeBytes.Length); ms.Write(fileNameBytes, 0, fileNameBytes.Length); byte[] fileContentBytes = File.ReadAllBytes(item.FullPath); ms.Write(BitConverter.GetBytes(fileContentBytes.Length), 0, 4); ms.Write(fileContentBytes, 0, fileContentBytes.Length); } ms.Flush(); ms.Position = 0; using (FileStream fs = File.Create(saveFullPath)) { using (GZipStream zipStream = new GZipStream(fs, CompressionMode.Compress)) { ms.CopyTo(zipStream); } } ms.Close();
2、压缩包解压以及文件解密
public void DeCompressMuti(string zipFileName,string targetPath) { byte[] fileSize = new byte[4]; if (!File.Exists(zipFileName)) return; using (FileStream fstream = File.Open(zipFileName, FileMode.Open)) { using (MemoryStream ms = new MemoryStream()) { using (GZipStream zipStream = new GZipStream(fstream, CompressionMode.Decompress)) { zipStream.CopyTo(ms); } ms.Position = 0; //获取总条数 ms.Read(fileSize, 0, fileSize.Length); int fileCountLength = BitConverter.ToInt32(fileSize, 0); byte[] fileCountBytes = new byte[fileCountLength]; ms.Read(fileCountBytes, 0, fileCountBytes.Length); string fileCount = Encoding.UTF8.GetString(fileCountBytes); while(ms.Position==ms.Length) { ms.Read(fileSize, 0, fileSize.Length); int fileNameLength = BitConverter.ToInt32(fileSize, 0); byte[] fileNameBytes = new byte[fileNameLength]; ms.Read(fileNameBytes, 0, fileNameBytes.Length); //数据解密 fileNameBytes = RSAHelper.RsaDecrypt(fileNameBytes, key); sting fileName = Encoding.UTF8.GetString(fileNameBytes); string fileFullName = targetPath + fileName; //获取文件 ms.Read(fileSize, 0, 4); int fileContentLength = BitConverter.ToInt32(fileSize, 0); byte[] fileContentBytes = new byte[fileContentLength]; ms.Read(fileContentBytes, 0, fileCountBytes.Length); using (FileStream ff = File.Create(fileFullName)) { ff.Write(fileCountBytes, 0, fileContentBytes.Length); } } } } }