using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.IO.Compression;
namespace WebDemo
{
public partial class FileCompAndDecomp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (RequestType())
{
string Message = string.Empty;
string HDCommand = Request["HDCommand"].ToString();
switch (HDCommand)
{
case "FileComp"://压缩
Message = CompressFile(Server.MapPath("yangfeizai/Temp.doc"), Server.MapPath("yangfeizai/Test.rar"));
break;
case "FileDeComp"://解压
Message = DecompressFile(Server.MapPath("yangfeizai/Test.rar"), Server.MapPath("yangfeizai/Result.doc"));
break;
default:
break;
}
Response.Write("<script>alert('" + Message + "')</script>");
}
}
#region //判断页面提交方式POST/GET
public bool RequestType()
{
if (HttpContext.Current.Request.RequestType == "POST")
return true;
else
return false;
}
#endregion
#region //文件压缩
public string CompressFile(string iFile, string oFile)
{
string message = string.Empty;
//判断文件是否存在
if (!File.Exists(iFile))
return "压缩文件未找到!";
//创建文件流
byte[] buffer = null;
FileStream iStream = null;
FileStream oStream = null;
GZipStream cStream = null;
try
{
//把文件写进数组
iStream = new FileStream(iFile, FileMode.Open, FileAccess.Read, FileShare.None);
buffer = new byte[iStream.Length];
int num = iStream.Read(buffer, 0, buffer.Length);
if (num != buffer.Length)
return "压缩文件出现异常!";
//创建文件输出流并输出
oStream = new FileStream(oFile, FileMode.Create, FileAccess.Write,FileShare.None);
cStream = new GZipStream(oStream, CompressionMode.Compress, true);
cStream.Write(buffer, 0, buffer.Length);
message = "压缩成功!";
}
catch (ApplicationException ex)
{
message=ex.Message;
}
finally
{
//关闭流对象
if (iStream != null) iStream.Close();
if (cStream != null) cStream.Close();
if (oStream != null) oStream.Close();
}
return message;
}
#endregion
#region //文件解压
public string DecompressFile(string iFile, string oFile)
{
string message = string.Empty;
//判断文件是否存在
if (!File.Exists(iFile))
return "解压文件为找到!";
//创建文件流
FileStream iStream = null;
FileStream oStream = null;
GZipStream dStream = null;
byte[] qBuffer = new byte[0x10000];
try
{
//把压缩文件写入数组
iStream = new FileStream(iFile, FileMode.Open, FileAccess.Read, FileShare.None);
dStream = new GZipStream(iStream, CompressionMode.Decompress, true);
//创建输出流并输出
oStream = new FileStream(oFile, FileMode.Create, FileAccess.Write, FileShare.None);
int bytesRead = dStream.Read(qBuffer, 0, qBuffer.Length);
while (bytesRead > 0)
{
oStream.Write(qBuffer, 0, bytesRead);
bytesRead = dStream.Read(qBuffer, 0, qBuffer.Length);
}
oStream.Flush();
message = "解压成功!";
}
catch (ApplicationException ex)
{
message = ex.Message;
}
finally
{
//关闭流对象
if (iStream != null) iStream.Close();
if (dStream != null) dStream.Close();
if (oStream != null) oStream.Close();
}
return message;
}
#endregion
}
}
.net 文件压缩和解压
最新推荐文章于 2024-09-11 17:44:36 发布