asp.net文件压缩,下载,物理路径,相对路径,删除文件
知识动手实践一次,就可以变成自己的了。不然一直是老师的,书本的。
这几天做了一个小小的项目,需要用到文件下载功能,期初想到只是单个的文件,后面想到如果很多文件怎么办?于是又想到文件压缩。几经波折实践,总是达到了我想要的效果了。现今把作为一个笔记记录下来,以便下次之用。
#region 物理路径和相对路径的转换
//本地路径转换成URL相对路径
public static string urlconvertor(string imagesurl1)
{
string tmpRootDir = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
string imagesurl2 = imagesurl1.Replace(tmpRootDir, ""); //转换成相对路径
imagesurl2 = imagesurl2.Replace(@"\", @"/");
//imagesurl2 = imagesurl2.Replace(@"Aspx_Uc/", @"");
return imagesurl2;
}
//相对路径转换成服务器本地物理路径
public static string urlconvertorlocal(string imagesurl1)
{
string tmpRootDir = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
string imagesurl2 = tmpRootDir + imagesurl1.Replace(@"/", @"\"); //转换成绝对路径
return imagesurl2;
}
#endregion /// <summary>
/// 获取物理地址
/// </summary>
public static string MapPathFile(string FileName)
{
return HttpContext.Current.Server.MapPath(FileName);
}
/// <summary>
/// 普通下载
/// </summary>
/// <param name="FileName">文件虚拟路径</param>
public static bool DownLoadold(string FileName)
{
bool bools = false;
string destFileName = FileName;// urlconvertor(FileName);// MapPathFile(FileName);
if (File.Exists(destFileName))
{
FileInfo fi = new FileInfo(destFileName);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = false;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(destFileName), System.Text.Encoding.UTF8));
HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(destFileName);
HttpContext.Current.Response.Flush();
AiLvYou.Common.DownUnit.FilePicDelete(destFileName);//删除当前下载的文件
HttpContext.Current.Response.End(); bools = true;
}
return bools;
}
//检查文件是否已经存在存在才下载
public static bool FileExists(string path)
{
bool ret = false;
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
ret = true;
}
return ret;
}
/// <summary>
/// 删除单个文件
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool FilePicDelete(string path)
{
bool ret = false;
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
file.Delete();
ret = true;
}
//else //删除目录
//{
// Directory.Delete(file );
//}
return ret;
} /// <summary>
/// 用递归方法删除文件夹目录及文件
/// </summary>
/// <param name="dir">带文件夹名的路径</param>
public static void DeleteFolder(string dir)
{
if (Directory.Exists(dir)) //如果存在这个文件夹删除之
{
foreach (string d in Directory.GetFileSystemEntries(dir))
{
if (File.Exists(d))
File.Delete(d); //直接删除其中的文件
else
DeleteFolder(d); //递归删除子文件夹
}
Directory.Delete(dir, true); //删除已空文件夹
}
}
第一种压缩方法 用WinRAR 需要安装此软件 ,而且压缩了整个目录,目前还没有解决
//会有整个目录
public void RARsave(string patch, string rarPatch, string rarName)
{
String the_rar;
RegistryKey the_Reg;
Object the_Obj;
String the_Info;
ProcessStartInfo the_StartInfo;
Process the_Process;
try
{
the_Reg = Registry.ClassesRoot.OpenSubKey(@"WinRAR"); the_Obj = the_Reg.GetValue("");
the_rar = the_Obj.ToString();
the_Reg.Close();
the_rar = the_rar.Substring(, the_rar.Length - ); Directory.CreateDirectory(patch);//20151222 //命令参数
//the_Info = " a " + rarName + " " + @"C:Test?70821.txt"; //文件压缩
the_Info = " a " + rarName + " " + patch +" -r";
the_StartInfo = new ProcessStartInfo();
the_StartInfo.FileName = "WinRar";//the_rar;
the_StartInfo.Arguments = the_Info;
the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
//打包文件存放目录
the_StartInfo.WorkingDirectory = rarPatch;
the_Process = new Process();
the_Process.StartInfo = the_StartInfo;
the_Process.Start();
the_Process.WaitForExit();
the_Process.Close(); }
catch (Exception ex)
{
throw ex;
}
}
/**//****************************************
* 函数名称:CopyDir
* 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
* 参 数:srcPath:原始路径,aimPath:目标文件夹
* 调用示列:
* string srcPath = Server.MapPath("test/");
* string aimPath = Server.MapPath("test1/");
* EC.FileObj.CopyDir(srcPath,aimPath);
*****************************************/
/**//// <summary>
/// 指定文件夹下面的所有内容copy到目标文件夹下面
/// </summary>
/// <param name="srcPath">原始路径</param>
/// <param name="aimPath">目标文件夹</param>
public static void CopyDir(string srcPath, string aimPath)
{
try
{
// 检查目标目录是否以目录分割字符结束如果不是则添加之
if (aimPath[aimPath.Length - ] != Path.DirectorySeparatorChar)
aimPath += Path.DirectorySeparatorChar;
// 判断目标目录是否存在如果不存在则新建之
if (!Directory.Exists(aimPath))
Directory.CreateDirectory(aimPath);
// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
//如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
//string[] fileList = Directory.GetFiles(srcPath);
string[] fileList = Directory.GetFileSystemEntries(srcPath);
//遍历所有的文件和目录
foreach (string file in fileList)
{
//先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 if (Directory.Exists(file))
CopyDir(file, aimPath + Path.GetFileName(file));
//否则直接Copy文件
else
File.Copy(file, aimPath + Path.GetFileName(file), true);
}
}
catch (Exception ee)
{
throw new Exception(ee.ToString());
}
}
使用代码:
protected void btndown_Click(object sender, EventArgs e)
{
string Folder = DateTime.Now.ToString("HHMMss");
string savefilepath = HttpContext.Current.Server.MapPath("/admin/ueditor/net/htmlfile/upload");
string savefilepath2 = HttpContext.Current.Server.MapPath("/admin/ueditor/net/htmlfile/upload/image"); string tempFolder = Path.Combine(savefilepath, Folder); Directory.CreateDirectory(tempFolder);
CopyDir(savefilepath2, tempFolder); // RARsave(@"D:\images", tempFolder, Folder);控制了解压目录但是没有文件
RARsave(tempFolder, tempFolder, Folder);
}
第二种压缩方法,使用了 ICSharpCode.SharpZipLib.dll 文件。先下载,放到bin目录下,然后引用。
实现代码
/// <summary>
/// 生成压缩文件
/// </summary>
/// <param name="strZipPath">生成的zip文件的路径</param>
/// <param name="strZipTopDirectoryPath">源文件的上级目录</param>
/// <param name="intZipLevel">T压缩等级</param>
/// <param name="strPassword">压缩包解压密码</param>
/// <param name="filesOrDirectoriesPaths">源文件路径</param>
/// <returns></returns>
private bool Zip(string strZipPath, string strZipTopDirectoryPath, int intZipLevel, string strPassword, string[] filesOrDirectoriesPaths)
{
try
{
List<string> AllFilesPath = new List<string>();
if (filesOrDirectoriesPaths.Length > ) // get all files path
{
for (int i = ; i < filesOrDirectoriesPaths.Length; i++)
{
if (File.Exists(filesOrDirectoriesPaths[i]))
{
AllFilesPath.Add(filesOrDirectoriesPaths[i]);
}
else if (Directory.Exists(filesOrDirectoriesPaths[i]))
{
GetDirectoryFiles(filesOrDirectoriesPaths[i], AllFilesPath);
}
}
} if (AllFilesPath.Count > )
{ ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(strZipPath));
zipOutputStream.SetLevel(intZipLevel);
zipOutputStream.Password = strPassword; for (int i = ; i < AllFilesPath.Count; i++)
{
string strFile = AllFilesPath[i].ToString();
try
{
if (strFile.Substring(strFile.Length - ) == "") //folder
{
string strFileName = strFile.Replace(strZipTopDirectoryPath, "");
if (strFileName.StartsWith(""))
{
strFileName = strFileName.Substring();
}
ZipEntry entry = new ZipEntry(strFileName);
entry.DateTime = DateTime.Now;
zipOutputStream.PutNextEntry(entry);
}
else //file
{
FileStream fs = File.OpenRead(strFile); byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length); string strFileName = strFile.Replace(strZipTopDirectoryPath, "");
if (strFileName.StartsWith(""))
{
strFileName = strFileName.Substring();
}
ZipEntry entry = new ZipEntry(strFileName);
entry.DateTime = DateTime.Now;
zipOutputStream.PutNextEntry(entry);
zipOutputStream.Write(buffer, , buffer.Length); fs.Close();
fs.Dispose();
}
}
catch
{
continue;
}
} zipOutputStream.Finish();
zipOutputStream.Close(); return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
/// <summary>
/// Gets the directory files.
/// </summary>
/// <param name="strParentDirectoryPath">源文件路径</param>
/// <param name="AllFilesPath">所有文件路径</param>
private void GetDirectoryFiles(string strParentDirectoryPath, List<string> AllFilesPath)
{
string[] files = Directory.GetFiles(strParentDirectoryPath);
for (int i = ; i < files.Length; i++)
{
AllFilesPath.Add(files[i]);
}
string[] directorys = Directory.GetDirectories(strParentDirectoryPath);
for (int i = ; i < directorys.Length; i++)
{
GetDirectoryFiles(directorys[i], AllFilesPath);
}
if (files.Length == && directorys.Length == ) //empty folder
{
AllFilesPath.Add(strParentDirectoryPath);
}
}
调用代码:
protected void btndowmload_Click(object sender, EventArgs e)
{
//http://www.cnblogs.com/LYunF/archive/2012/02/18/2357591.html string Folder = DateTime.Now.ToString("HHMMss");
string savefilepath = HttpContext.Current.Server.MapPath("/admin/ueditor/net/htmlfile/upload");
string savefilepath2 = HttpContext.Current.Server.MapPath("/admin/ueditor/net/htmlfile/upload/image"); // 判断目标目录是否存在如果不存在则新建之
/*
string newfilepath = Path.Combine(savefilepath, Folder);
if (!Directory.Exists(newfilepath))
Directory.CreateDirectory(newfilepath);//问题目录问题
string newfilepath2 = HttpContext.Current.Server.MapPath("/admin/ueditor/net/htmlfile/upload"+"/"+Folder);
string strZipTopDirectoryPath = newfilepath2;
string tempFolder = Path.Combine(newfilepath2, Folder); */
string tempFolder = Path.Combine(savefilepath, Folder);
string strZipTopDirectoryPath = savefilepath;
string strZipPath = tempFolder + ".zip";
int intZipLevel = ;
string strPassword = "";
string[] filesOrDirectoriesPaths = new string[] { savefilepath2 };
bool flag = Zip(strZipPath, strZipTopDirectoryPath, intZipLevel, strPassword, filesOrDirectoriesPaths);
if (flag)
{
ResponseFile(strZipPath);
}
}
下载代码:
protected void ResponseFile(string fileName)
{ FileInfo fileInfo = new FileInfo(fileName);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
// Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); //upload 这里可以改变下载名称
Response.AddHeader("Content-Disposition", "attachment;filename=upload.zip"); //
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();
// string tempPath = fileName.Substring(0, fileName.LastIndexOf("\\"));
AiLvYou.Common.DownUnit.FilePicDelete(fileName);
// Directory.Delete(tempPath);
Response.End(); }
asp.net文件压缩,下载,物理路径,相对路径,删除文件的更多相关文章
- 文件压缩、解压工具类。文件压缩格式为zip
package com.JUtils.file; import java.io.BufferedOutputStream; import java.io.File; import java.io.Fi ...
- php多文件压缩下载
/*php多文件压缩并且下载*/ function addFileToZip($path,$zip){ $handler=opendir($path); //打开当前文件夹由$path指定. whil ...
- Java 多个文件压缩下载
有时候会有多个附件一起下载的需求,这个时候最好就是打包下载了 首先下面这段代码是正常的单个下载 public void Download(@RequestParam("file_path&q ...
- linux文件权限总结(创建root不可以删除文件、只可追加的日志文件等)
文件类型 对于文件和目录的访问权力是根据读访问,写访问,和执行访问来定义的. 我们来看一下 ls 命令的输出结果 [root@iZ28dr6w0qvZ test]# ls -l 总用量 72 -rw- ...
- asp.net mvc 文件压缩下载
压缩文件相关的类: public class ZIPCompressUtil { public static Tuple<bool, Stream> Zip(string strZipTo ...
- ftp多文件压缩下载
@GetMapping(value = "/find") public String findfile(String filePath, String fileNames, Htt ...
- java多个文件压缩下载
public static void zipFiles(File[] srcfile,ServletOutputStream sos){ byte[] buf=new byte[1024]; try ...
- UIwebview 文件的下载与保存,以及mp3文件的播放
这里只是说说异步 单线程下载与文件的保存 以下载一个mp3文件并保存为例: -(void)loading { //设置文件下载地址 NSString *urlString = [NSString st ...
- 【2017-05-30】WebForm文件上传。从服务端删除文件
用 FileUpload控件进行上传文件. <asp:FileUpload ID="FileUpload1" runat="server" /> ...
- 用Spring中的ResponseEntity文件批量压缩下载
我看了很多网上的demo,先生成ZIP压缩文件,然后再下载. 我这里是生成ZIP文件流 进行下载.(核心代码没多少,就是一些业务代码) @RequestMapping(value = "/& ...
随机推荐
- Windows中的时间(SYSTEMTIME和FILETIME) (转载)
转载:http://blog.csdn.net/bokee/article/details/5330791 两种时间系统之间没有本质区别(事实上CRT时间是用Windows时间实现的,当然这是说的VC ...
- 获取mips32机器的各数据类型的取值范围
一.背景: 使用的mips 32bit机器,32bit的vxworks操作系统(各机器带来的范围都不一样,与操作系统也有关联) 二.验证类型的范围: 2.1 unsigned long: void m ...
- 蚂蚁感冒|2014年蓝桥杯B组题解析第八题-fishers
蚂蚁感冒 长100厘米的细长直杆子上有n只蚂蚁.它们的头有的朝左,有的朝右. 每只蚂蚁都只能沿着杆子向前爬,速度是1厘米/秒. 当两只蚂蚁碰面时,它们会同时掉头往相反的方向爬行. 这些蚂蚁中,有1只蚂 ...
- Codeforces Round #527 (Div. 3)
一场div3... 由于不计rating,所以打的比较浪,zhy直接开了个小号来掉分,于是他AK做出来了许多神仙题,但是在每一个程序里都是这么写的: 但是..sbzhy每题交了两次,第一遍都是对的,结 ...
- 整理ASP.NET MVC 5各种错误请求[401,403,404,500]的拦截及自定义页面处理实例
http://2sharings.com/2015/asp-net-mvc-5-custom-404-500-error-hanlde https://blog.csdn.net/yhyhyhy/ar ...
- Unity3D学习笔记(十):Physics类和射线
物理系统:碰撞器.触发器等 力:有大小有方向的矢量,有受力点位置(和向量的区别) ----F = ma(m质量,a加速度,质量越大,加速度越小,停下来越慢) ----m1v1 = m2v2(冲量守恒定 ...
- C#学习笔记(十三):继承
继承 object是引用类型 public:最高权限,公开的 Protected:外部不可以访问 Internal:类的默认访问是什么作用域 Private:类成员默认 基类实例:可以通过base ...
- HDU 1548 A strange lift (Dijkstra)
https://vjudge.net/problem/HDU-1548 题意: 电梯每层有一个不同的数字,例如第n层有个数字k,那么这一层只能上k层或下k层,但是不能低于一层或高于n层,给定起点与终点 ...
- Codeforces Round #323 (Div. 2) D. Once Again... 乱搞+LIS
D. Once Again... time limit per test 1 second memory limit per test 256 megabytes input standard inp ...
- go 通道
1. package main import "fmt" func sum(s []int, c chan int) { sum := for _, v := range s { ...