项目上下载需要将大文件压缩成多个小文件.然后再解压出来.
1.获取所有文件,并加载到内存流中. 注意: 指定的文件最后读取. 比如:
x86.z01
x86.z02
x86.z03
x86.zip
读取到流中的顺序是入上所列出的顺序否则解压会报错.
//读取文件,并过滤("x86*")
//读取指定目录中的文件
string[] fileNames = Directory.GetFiles(sourceDir, searchPattern);
if (fileNames == null || fileNames.Length == 0)
{
throw new Exception("压缩文件异常");
}
//将所有文件读取出来,然后放到内存流中
System.IO.MemoryStream mStream = new MemoryStream();
//先读取指定文件
byte[] tBytes = null;
//循环读取所有文件
string tfileName = null;
foreach (var fileItem in fileNames)
{
tfileName = System.IO.Path.GetFileName(fileItem).ToLower();
//排除zip指定文件,让其最后加载
if (zipfileName == tfileName)
{
continue;
}
tBytes = File.ReadAllBytes(fileItem);
mStream.Write(tBytes, 0, tBytes.Length);
}
tBytes = File.ReadAllBytes(sourceDir + zipfileName);
mStream.Write(tBytes, 0, tBytes.Length);
//注意必须设置Pos=0,否则会报EOF异常
mStream.Position = 0;
所有代码
public static void ZIPDecompress(string sourceDir, string targetPath, string zipfileName, string searchPattern)
{
#region 判断参数
const string ENDPATHFLG = "\\";
zipfileName = zipfileName.ToLower();
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
//添加标记
if (sourceDir.EndsWith(ENDPATHFLG) == false)
{
sourceDir += ENDPATHFLG;
}
if (targetPath.EndsWith(ENDPATHFLG) == false)
{
targetPath += ENDPATHFLG;
}
if (!File.Exists(sourceDir + zipfileName))
{
throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", sourceDir));
}
#endregion
//读取文件,并过滤("x86*")
string[] fileNames = Directory.GetFiles(sourceDir, searchPattern);
if (fileNames == null || fileNames.Length == 0)
{
throw new Exception("压缩文件异常");
}
//将所有文件读取出来,然后放到内存流中
System.IO.MemoryStream mStream = new MemoryStream();
//先读取指定文件
byte[] tBytes = null;
//循环读取所有文件
string tfileName = null;
foreach (var fileItem in fileNames)
{
tfileName = System.IO.Path.GetFileName(fileItem).ToLower();
//排除zip指定文件,让其最后加载
if (zipfileName == tfileName)
{
continue;
}
tBytes = File.ReadAllBytes(fileItem);
mStream.Write(tBytes, 0, tBytes.Length);
}
tBytes = File.ReadAllBytes(sourceDir + zipfileName);
mStream.Write(tBytes, 0, tBytes.Length);
//注意必须设置Pos=0,否则会报EOF异常
mStream.Position = 0;
using (ZipInputStream s = new ZipInputStream(mStream))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directorName = Path.Combine(targetPath, Path.GetDirectoryName(theEntry.Name));
string fileName = Path.Combine(directorName, Path.GetFileName(theEntry.Name));
// 创建目录
if (directorName.Length > 0)
{
Directory.CreateDirectory(directorName);
}
if (fileName != string.Empty)
{
using (FileStream streamWriter = File.Create(fileName))
{
int size = 4096;
byte[] data = new byte[4 * 1024];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else break;
}
}
}
}
}
mStream.Close();
}