批量打包下载与上传解压

--------------打包下载压缩---------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;

namespace dabaoRar
{
public partial class download : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
//DirectoryInfo TheFolder = new DirectoryInfo(Server.MapPath("Resource/Help"));//遍历
DirectoryInfo TheFolder = new DirectoryInfo(@"D:\宁国移动执法监察数据同步\业务数据导出");//遍历

if (!TheFolder.Exists)
return;

List<string> listFJ = new List<string>();
List<string> listFJName = new List<string>();
foreach (FileInfo NextFile in TheFolder.GetFiles())
{
listFJ.Add(NextFile.FullName);
listFJName.Add(NextFile.Name);
}
string time = DateTime.Now.Ticks.ToString();////////////////////////////////////////////
ZipFileMain(listFJ.ToArray(), listFJName.ToArray(), Server.MapPath("Resource/" + time + ".zip"), 9);//压缩文件
DownloadFile(Server.UrlEncode("业务数据.zip"), Server.MapPath("Resource/" + time + ".zip"));//下载文件
}
//下载
private void DownloadFile(string fileName, string filePath)
{
FileInfo fileInfo = new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
File.Delete(filePath);//删除已下载文件
Response.End();
}
//压缩
public void ZipFileMain(string[] filenames, string[] filename, string name, int Level)
{
ZipOutputStream s = new ZipOutputStream(File.Create(name));
Crc32 crc = new Crc32();
s.SetLevel(Level);

try
{
int m = 0;
foreach (var file in filenames)
{
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(filename[m].ToString());
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
m++;

}
}
catch (Exception)
{

throw;
}
finally
{
s.Finish();
s.Close();
}


}
}
}

--------------上传解压---------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;
using NGZFJC.Business_ZFJC.App_Code;
using Microsoft.Win32;
using System.Diagnostics;

namespace NGZFJC.Business_ZFJC.WebForms
{
public partial class upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();
if (fileExtension == ".zip")
{
string fileName = FileUpload1.FileName;
//Path.GetDirectoryName(
string path = Request.MapPath("Resource/" + fileName);
FileUpload1.SaveAs(path);
//string path1 = Request.MapPath("Resource/doc/");

try
{
UnpackFileRarOrZip(path, @"D:\软件\宁国系统\移动执法监察\数据交换\业务数据导入");
Response.Write("<script>alert('上传成功!');</script>");
}
catch (Exception)
{
Response.Write("<script>alert('上传失败!');</script>");
}
}
else
{
Response.Write("<script>alert('文件格式不正确!');</script>");
}

}
else
{
Response.Write("<script>alert('您还没有选择文件!');</script>");
}

#region 原始的
//if (FileUpload1.HasFile)
//{
// string fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();
// if (fileExtension == ".zip")
// {
// string fileName = FileUpload1.FileName;
// //Path.GetDirectoryName(
// string path = Request.MapPath("Resource/" + fileName);
// FileUpload1.SaveAs(path);
// //string path1 = Request.MapPath("Resource/doc/");

// try
// {
// Decompress(path, @"D:\软件\宁国系统\移动执法监察\数据交换\业务数据导入");
// Response.Write("<script>alert('上传成功!');</script>");
// }
// catch (Exception)
// {
// Response.Write("<script>alert('上传失败!');</script>");
// }
// }
// else
// {
// Response.Write("<script>alert('文件格式不正确!');</script>");
// }

//}
//else
//{
// Response.Write("<script>alert('您还没有选择文件!');</script>");
//}
#endregion
}

#region 解压缩
/// <summary>
/// 解压缩
/// </summary>
/// <param name="sourceFile">压缩包完整路径地址</param>
/// <param name="targetPath">解压路径是哪里</param>
/// <returns></returns>
public static bool Decompress(string sourceFile, string targetPath)
{
if (!File.Exists(sourceFile))
{
throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", sourceFile));
}
if (!Directory.Exists(targetPath))
{
Directory.CreateDirectory(targetPath);
}
using (var s = new ZipInputStream(File.OpenRead(sourceFile)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.IsDirectory)
{
continue;
}
string directorName = Path.Combine(targetPath, Path.GetDirectoryName(theEntry.Name));
string fileName = Path.Combine(directorName, Path.GetFileName(theEntry.Name));
if (!Directory.Exists(directorName))
{
Directory.CreateDirectory(directorName);
}
if (!String.IsNullOrEmpty(fileName))
{
using (FileStream streamWriter = File.Create(fileName))
{
int size = 2048;
byte[] data = new byte[size];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}

}
}
}
}
}
return true;
}
#endregion

#region 解压文件 包括.rar 和zip

/// <summary>
///解压文件
/// </summary>
/// <param name="fileFromUnZip">解压前的文件路径(绝对路径)</param>
/// <param name="fileToUnZip">解压后的文件目录(绝对路径)</param>
public static void UnpackFileRarOrZip(string fileFromUnZip, string fileToUnZip)
{
//获取压缩类型
string unType = fileFromUnZip.Substring(fileFromUnZip.LastIndexOf(".") + 1, 3).ToLower();

switch (unType)
{
case "rar":
UnRar(fileFromUnZip, fileToUnZip);
break;
default:
UnZip(fileFromUnZip, fileToUnZip);
break;

}
}


#endregion

 

#region 解压文件 .rar文件

/// <summary>
/// 解压
/// </summary>
/// <param name="unRarPatch"></param>
/// <param name="rarPatch"></param>
/// <param name="rarName"></param>
/// <returns></returns>
public static void UnRar(string fileFromUnZip, string fileToUnZip)
{
string the_rar;
RegistryKey the_Reg;
object the_Obj;
string the_Info;

try
{
the_Reg = Registry.LocalMachine.OpenSubKey(
@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
the_Obj = the_Reg.GetValue("");
the_rar = the_Obj.ToString();
the_Reg.Close();
//the_rar = the_rar.Substring(1, the_rar.Length - 7);

if (Directory.Exists(fileToUnZip) == false)
{
Directory.CreateDirectory(fileToUnZip);
}
the_Info = "x " + Path.GetFileName(fileFromUnZip) + " " + fileToUnZip + " -y";

ProcessStartInfo the_StartInfo = new ProcessStartInfo();
the_StartInfo.FileName = the_rar;
the_StartInfo.Arguments = the_Info;
the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
the_StartInfo.WorkingDirectory = Path.GetDirectoryName(fileFromUnZip);//获取压缩包路径

Process the_Process = new Process();
the_Process.StartInfo = the_StartInfo;
the_Process.Start();
the_Process.WaitForExit();
the_Process.Close();
}
catch (Exception ex)
{
throw ex;
}
//return unRarPatch;
}

#endregion

 

#region 解压文件 .zip文件

/// <summary>
/// 解压功能(解压压缩文件到指定目录)
/// </summary>
/// <param name="FileToUpZip">待解压的文件</param>
/// <param name="ZipedFolder">指定解压目标目录</param>
public static void UnZip(string FileToUpZip, string ZipedFolder)
{
if (!File.Exists(FileToUpZip))
{
return;
}

if (!Directory.Exists(ZipedFolder))
{
Directory.CreateDirectory(ZipedFolder);
}

ICSharpCode.SharpZipLib.Zip.ZipInputStream s = null;
ICSharpCode.SharpZipLib.Zip.ZipEntry theEntry = null;

string fileName;
FileStream streamWriter = null;
try
{
s = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(FileToUpZip));
while ((theEntry = s.GetNextEntry()) != null)
{

if (theEntry.Name != String.Empty)
{
fileName = Path.Combine(ZipedFolder, theEntry.Name);
///判断文件路径是否是文件夹

if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
{
Directory.CreateDirectory(fileName);
continue;
}

streamWriter = File.Create(fileName);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
finally
{
if (streamWriter != null)
{
streamWriter.Close();
streamWriter = null;
}
if (theEntry != null)
{
theEntry = null;
}
if (s != null)
{
s.Close();
s = null;
}
GC.Collect();
GC.Collect(1);
}
}


#endregion
}
}

 

posted @ 2017-04-06 10:05  我在码头等你  阅读(217)  评论(0编辑  收藏  举报