C#创建的ZIP文件无效
我试图将多个文件压缩到一个zip文件,但生成的zip文件无效,我的代码在这里,我不知道这里出了什么问题C#创建的ZIP文件无效,c#,C#,我试图将多个文件压缩到一个zip文件,但生成的zip文件无效,我的代码在这里,我不知道这里出了什么问题 public static void DownloadRQFFiles(string[] sourceFileList, string saveFullPath) { MemoryStream ms = new MemoryStream(); foreach (string filePath in sourceFileList) { Console.Wr
public static void DownloadRQFFiles(string[] sourceFileList, string saveFullPath)
{
MemoryStream ms = new MemoryStream();
foreach (string filePath in sourceFileList)
{
Console.WriteLine(filePath);
if (File.Exists(filePath))
{
string fileName = Path.GetFileName(filePath);
byte[] fileNameBytes = System.Text.Encoding.UTF8.GetBytes(fileName);
byte[] sizeBytes = BitConverter.GetBytes(fileNameBytes.Length);
ms.Write(sizeBytes, 0, sizeBytes.Length);
ms.Write(fileNameBytes, 0, fileNameBytes.Length);
byte[] fileContentBytes = System.IO.File.ReadAllBytes(filePath);
ms.Write(BitConverter.GetBytes(fileContentBytes.Length), 0, 4);
ms.Write(fileContentBytes, 0, fileContentBytes.Length);
}
}
ms.Flush();
ms.Position = 0;
using (FileStream zipFileStream = File.Create(saveFullPath))
{
using (GZipStream zipStream = new GZipStream(zipFileStream, CompressionMode.Compress))
{
ms.Position = 0;
ms.CopyTo(zipStream);
}
}
ms.Close();
}
请参阅Microsoft文档以获取帮助。这是谷歌上的第一个结果:
using System;
using System.IO;
using System.IO.Compression;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
其中,startPath
是包含要压缩在一起的文件的目录,zipPath
是要创建压缩文件的目录,extractPath
是应该提取这些文件的目录(示例显示了压缩和提取)
有关如何利用System.IO.Compression
命名空间的更多示例,请访问下面提供的源代码
GZipStream生成.gz文件。也许你想用它来代替?据我所知,GZipStream不适合处理多个文件,因为它没有任何需要的文件头或基础结构信息。@IanBoggs,是的,GZipStream只能处理单个文件,所以我将所有内容写入一个文件“ms”首先。@sven.xia那么你以后是如何压缩文件的?@IanBoggs我使用了GZip…但它似乎生成了.gz文件。我不确定,我不能使用第三方名称空间,所以我尝试了GZip…谢谢。那有点不同。源文件可能来自不同的路径,如@“c:\example\test1.txt”、“c:\temp\test2.txt”等。它们的完整路径存储在字符串数组中。但您仍然可以使用我提供的MSDN链接来执行此操作