知识动手实践一次,就可以变成自己的了。不然一直是老师的,书本的。

这几天做了一个小小的项目,需要用到文件下载功能,期初想到只是单个的文件,后面想到如果很多文件怎么办?于是又想到文件压缩。几经波折实践,总是达到了我想要的效果了。现今把作为一个笔记记录下来,以便下次之用。

  1. #region 物理路径和相对路径的转换
  2. //本地路径转换成URL相对路径
  3. public static string urlconvertor(string imagesurl1)
  4. {
  5. string tmpRootDir = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
  6. string imagesurl2 = imagesurl1.Replace(tmpRootDir, ""); //转换成相对路径
  7. imagesurl2 = imagesurl2.Replace(@"\", @"/");
  8. //imagesurl2 = imagesurl2.Replace(@"Aspx_Uc/", @"");
  9. return imagesurl2;
  10. }
  11. //相对路径转换成服务器本地物理路径
  12. public static string urlconvertorlocal(string imagesurl1)
  13. {
  14. string tmpRootDir = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
  15. string imagesurl2 = tmpRootDir + imagesurl1.Replace(@"/", @"\"); //转换成绝对路径
  16. return imagesurl2;
  17. }
  18. #endregion
  19.  
  20. /// <summary>
  21. /// 获取物理地址
  22. /// </summary>
  23. public static string MapPathFile(string FileName)
  24. {
  25. return HttpContext.Current.Server.MapPath(FileName);
  26. }
  27. /// <summary>
  28. /// 普通下载
  29. /// </summary>
  30. /// <param name="FileName">文件虚拟路径</param>
  31. public static bool DownLoadold(string FileName)
  32. {
  33. bool bools = false;
  34. string destFileName = FileName;// urlconvertor(FileName);// MapPathFile(FileName);
  35. if (File.Exists(destFileName))
  36. {
  37. FileInfo fi = new FileInfo(destFileName);
  38. HttpContext.Current.Response.Clear();
  39. HttpContext.Current.Response.ClearHeaders();
  40. HttpContext.Current.Response.Buffer = false;
  41. HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(destFileName), System.Text.Encoding.UTF8));
  42. HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
  43. HttpContext.Current.Response.ContentType = "application/octet-stream";
  44. HttpContext.Current.Response.WriteFile(destFileName);
  45. HttpContext.Current.Response.Flush();
  46. AiLvYou.Common.DownUnit.FilePicDelete(destFileName);//删除当前下载的文件
  47. HttpContext.Current.Response.End();
  48.  
  49. bools = true;
  50. }
  51. return bools;
  52. }
  1. //检查文件是否已经存在存在才下载
  2. public static bool FileExists(string path)
  3. {
  4. bool ret = false;
  5. System.IO.FileInfo file = new System.IO.FileInfo(path);
  6. if (file.Exists)
  7. {
  8. ret = true;
  9. }
  10. return ret;
  11. }
  12. /// <summary>
  13. /// 删除单个文件
  14. /// </summary>
  15. /// <param name="path"></param>
  16. /// <returns></returns>
  17. public static bool FilePicDelete(string path)
  18. {
  19. bool ret = false;
  20. System.IO.FileInfo file = new System.IO.FileInfo(path);
  21. if (file.Exists)
  22. {
  23. file.Delete();
  24. ret = true;
  25. }
  26. //else //删除目录
  27. //{
  28. // Directory.Delete(file );
  29. //}
  30. return ret;
  31. }
  32.  
  33. /// <summary>
  34. /// 用递归方法删除文件夹目录及文件
  35. /// </summary>
  36. /// <param name="dir">带文件夹名的路径</param>
  37. public static void DeleteFolder(string dir)
  38. {
  39. if (Directory.Exists(dir)) //如果存在这个文件夹删除之
  40. {
  41. foreach (string d in Directory.GetFileSystemEntries(dir))
  42. {
  43. if (File.Exists(d))
  44. File.Delete(d); //直接删除其中的文件
  45. else
  46. DeleteFolder(d); //递归删除子文件夹
  47. }
  48. Directory.Delete(dir, true); //删除已空文件夹
  49. }
  50. }

第一种压缩方法 用WinRAR 需要安装此软件 ,而且压缩了整个目录,目前还没有解决

  1. //会有整个目录
  2. public void RARsave(string patch, string rarPatch, string rarName)
  3. {
  4. String the_rar;
  5. RegistryKey the_Reg;
  6. Object the_Obj;
  7. String the_Info;
  8. ProcessStartInfo the_StartInfo;
  9. Process the_Process;
  10. try
  11. {
  12. the_Reg = Registry.ClassesRoot.OpenSubKey(@"WinRAR");
  13.  
  14. the_Obj = the_Reg.GetValue("");
  15. the_rar = the_Obj.ToString();
  16. the_Reg.Close();
  17. the_rar = the_rar.Substring(, the_rar.Length - );
  18.  
  19. Directory.CreateDirectory(patch);//20151222
  20.  
  21. //命令参数
  22. //the_Info = " a " + rarName + " " + @"C:Test?70821.txt"; //文件压缩
  23. the_Info = " a " + rarName + " " + patch +" -r";
  24. the_StartInfo = new ProcessStartInfo();
  25. the_StartInfo.FileName = "WinRar";//the_rar;
  26. the_StartInfo.Arguments = the_Info;
  27. the_StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  28. //打包文件存放目录
  29. the_StartInfo.WorkingDirectory = rarPatch;
  30. the_Process = new Process();
  31. the_Process.StartInfo = the_StartInfo;
  32. the_Process.Start();
  33. the_Process.WaitForExit();
  34. the_Process.Close();
  35.  
  36. }
  37. catch (Exception ex)
  38. {
  39. throw ex;
  40. }
  41. }
  1. /**//****************************************
  2. * 函数名称:CopyDir
  3. * 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
  4. * 参 数:srcPath:原始路径,aimPath:目标文件夹
  5. * 调用示列:
  6. * string srcPath = Server.MapPath("test/");
  7. * string aimPath = Server.MapPath("test1/");
  8. * EC.FileObj.CopyDir(srcPath,aimPath);
  9. *****************************************/
  10. /**//// <summary>
  11. /// 指定文件夹下面的所有内容copy到目标文件夹下面
  12. /// </summary>
  13. /// <param name="srcPath">原始路径</param>
  14. /// <param name="aimPath">目标文件夹</param>
  15. public static void CopyDir(string srcPath, string aimPath)
  16. {
  17. try
  18. {
  19. // 检查目标目录是否以目录分割字符结束如果不是则添加之
  20. if (aimPath[aimPath.Length - ] != Path.DirectorySeparatorChar)
  21. aimPath += Path.DirectorySeparatorChar;
  22. // 判断目标目录是否存在如果不存在则新建之
  23. if (!Directory.Exists(aimPath))
  24. Directory.CreateDirectory(aimPath);
  25. // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
  26. //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
  27. //string[] fileList = Directory.GetFiles(srcPath);
  28. string[] fileList = Directory.GetFileSystemEntries(srcPath);
  29. //遍历所有的文件和目录
  30. foreach (string file in fileList)
  31. {
  32. //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
  33.  
  34. if (Directory.Exists(file))
  35. CopyDir(file, aimPath + Path.GetFileName(file));
  36. //否则直接Copy文件
  37. else
  38. File.Copy(file, aimPath + Path.GetFileName(file), true);
  39. }
  40. }
  41. catch (Exception ee)
  42. {
  43. throw new Exception(ee.ToString());
  44. }
  45. }

使用代码:

  1. protected void btndown_Click(object sender, EventArgs e)
  2. {
  3. string Folder = DateTime.Now.ToString("HHMMss");
  4. string savefilepath = HttpContext.Current.Server.MapPath("/admin/ueditor/net/htmlfile/upload");
  5. string savefilepath2 = HttpContext.Current.Server.MapPath("/admin/ueditor/net/htmlfile/upload/image");
  6.  
  7. string tempFolder = Path.Combine(savefilepath, Folder);
  8.  
  9. Directory.CreateDirectory(tempFolder);
  10. CopyDir(savefilepath2, tempFolder);
  11.  
  12. // RARsave(@"D:\images", tempFolder, Folder);控制了解压目录但是没有文件
  13. RARsave(tempFolder, tempFolder, Folder);
  14. }

第二种压缩方法,使用了 ICSharpCode.SharpZipLib.dll 文件。先下载,放到bin目录下,然后引用。

实现代码

  1. /// <summary>
  2. /// 生成压缩文件
  3. /// </summary>
  4. /// <param name="strZipPath">生成的zip文件的路径</param>
  5. /// <param name="strZipTopDirectoryPath">源文件的上级目录</param>
  6. /// <param name="intZipLevel">T压缩等级</param>
  7. /// <param name="strPassword">压缩包解压密码</param>
  8. /// <param name="filesOrDirectoriesPaths">源文件路径</param>
  9. /// <returns></returns>
  10. private bool Zip(string strZipPath, string strZipTopDirectoryPath, int intZipLevel, string strPassword, string[] filesOrDirectoriesPaths)
  11. {
  12. try
  13. {
  14. List<string> AllFilesPath = new List<string>();
  15. if (filesOrDirectoriesPaths.Length > ) // get all files path
  16. {
  17. for (int i = ; i < filesOrDirectoriesPaths.Length; i++)
  18. {
  19. if (File.Exists(filesOrDirectoriesPaths[i]))
  20. {
  21. AllFilesPath.Add(filesOrDirectoriesPaths[i]);
  22. }
  23. else if (Directory.Exists(filesOrDirectoriesPaths[i]))
  24. {
  25. GetDirectoryFiles(filesOrDirectoriesPaths[i], AllFilesPath);
  26. }
  27. }
  28. }
  29.  
  30. if (AllFilesPath.Count > )
  31. {
  32.  
  33. ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(strZipPath));
  34. zipOutputStream.SetLevel(intZipLevel);
  35. zipOutputStream.Password = strPassword;
  36.  
  37. for (int i = ; i < AllFilesPath.Count; i++)
  38. {
  39. string strFile = AllFilesPath[i].ToString();
  40. try
  41. {
  42. if (strFile.Substring(strFile.Length - ) == "") //folder
  43. {
  44. string strFileName = strFile.Replace(strZipTopDirectoryPath, "");
  45. if (strFileName.StartsWith(""))
  46. {
  47. strFileName = strFileName.Substring();
  48. }
  49. ZipEntry entry = new ZipEntry(strFileName);
  50. entry.DateTime = DateTime.Now;
  51. zipOutputStream.PutNextEntry(entry);
  52. }
  53. else //file
  54. {
  55. FileStream fs = File.OpenRead(strFile);
  56.  
  57. byte[] buffer = new byte[fs.Length];
  58. fs.Read(buffer, , buffer.Length);
  59.  
  60. string strFileName = strFile.Replace(strZipTopDirectoryPath, "");
  61. if (strFileName.StartsWith(""))
  62. {
  63. strFileName = strFileName.Substring();
  64. }
  65. ZipEntry entry = new ZipEntry(strFileName);
  66. entry.DateTime = DateTime.Now;
  67. zipOutputStream.PutNextEntry(entry);
  68. zipOutputStream.Write(buffer, , buffer.Length);
  69.  
  70. fs.Close();
  71. fs.Dispose();
  72. }
  73. }
  74. catch
  75. {
  76. continue;
  77. }
  78. }
  79.  
  80. zipOutputStream.Finish();
  81. zipOutputStream.Close();
  82.  
  83. return true;
  84. }
  85. else
  86. {
  87. return false;
  88. }
  89. }
  90. catch
  91. {
  92. return false;
  93. }
  94. }
  95. /// <summary>
  96. /// Gets the directory files.
  97. /// </summary>
  98. /// <param name="strParentDirectoryPath">源文件路径</param>
  99. /// <param name="AllFilesPath">所有文件路径</param>
  100. private void GetDirectoryFiles(string strParentDirectoryPath, List<string> AllFilesPath)
  101. {
  102. string[] files = Directory.GetFiles(strParentDirectoryPath);
  103. for (int i = ; i < files.Length; i++)
  104. {
  105. AllFilesPath.Add(files[i]);
  106. }
  107. string[] directorys = Directory.GetDirectories(strParentDirectoryPath);
  108. for (int i = ; i < directorys.Length; i++)
  109. {
  110. GetDirectoryFiles(directorys[i], AllFilesPath);
  111. }
  112. if (files.Length == && directorys.Length == ) //empty folder
  113. {
  114. AllFilesPath.Add(strParentDirectoryPath);
  115. }
  116. }

调用代码:

  1. protected void btndowmload_Click(object sender, EventArgs e)
  2. {
  3. //http://www.cnblogs.com/LYunF/archive/2012/02/18/2357591.html
  4.  
  5. string Folder = DateTime.Now.ToString("HHMMss");
  6. string savefilepath = HttpContext.Current.Server.MapPath("/admin/ueditor/net/htmlfile/upload");
  7. string savefilepath2 = HttpContext.Current.Server.MapPath("/admin/ueditor/net/htmlfile/upload/image");
  8.  
  9. // 判断目标目录是否存在如果不存在则新建之
  10. /*
  11. string newfilepath = Path.Combine(savefilepath, Folder);
  12. if (!Directory.Exists(newfilepath))
  13. Directory.CreateDirectory(newfilepath);//问题目录问题
  14. string newfilepath2 = HttpContext.Current.Server.MapPath("/admin/ueditor/net/htmlfile/upload"+"/"+Folder);
  15. string strZipTopDirectoryPath = newfilepath2;
  16. string tempFolder = Path.Combine(newfilepath2, Folder);
  17.  
  18. */
  19. string tempFolder = Path.Combine(savefilepath, Folder);
  20. string strZipTopDirectoryPath = savefilepath;
  21. string strZipPath = tempFolder + ".zip";
  22. int intZipLevel = ;
  23. string strPassword = "";
  24. string[] filesOrDirectoriesPaths = new string[] { savefilepath2 };
  25. bool flag = Zip(strZipPath, strZipTopDirectoryPath, intZipLevel, strPassword, filesOrDirectoriesPaths);
  26. if (flag)
  27. {
  28. ResponseFile(strZipPath);
  29. }
  30. }

下载代码:

  1. protected void ResponseFile(string fileName)
  2. {
  3.  
  4. FileInfo fileInfo = new FileInfo(fileName);
  5. Response.Clear();
  6. Response.ClearContent();
  7. Response.ClearHeaders();
  8. // Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); //upload 这里可以改变下载名称
  9. Response.AddHeader("Content-Disposition", "attachment;filename=upload.zip"); //
  10. Response.AddHeader("Content-Length", fileInfo.Length.ToString());
  11. Response.AddHeader("Content-Transfer-Encoding", "binary");
  12. Response.ContentType = "application/octet-stream";
  13. Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
  14. Response.WriteFile(fileInfo.FullName);
  15. Response.Flush();
  16. // string tempPath = fileName.Substring(0, fileName.LastIndexOf("\\"));
  17. AiLvYou.Common.DownUnit.FilePicDelete(fileName);
  18. // Directory.Delete(tempPath);
  19. Response.End();
  20.  
  21. }

asp.net文件压缩,下载,物理路径,相对路径,删除文件的更多相关文章

  1. 文件压缩、解压工具类。文件压缩格式为zip

    package com.JUtils.file; import java.io.BufferedOutputStream; import java.io.File; import java.io.Fi ...

  2. php多文件压缩下载

    /*php多文件压缩并且下载*/ function addFileToZip($path,$zip){ $handler=opendir($path); //打开当前文件夹由$path指定. whil ...

  3. Java 多个文件压缩下载

    有时候会有多个附件一起下载的需求,这个时候最好就是打包下载了 首先下面这段代码是正常的单个下载 public void Download(@RequestParam("file_path&q ...

  4. linux文件权限总结(创建root不可以删除文件、只可追加的日志文件等)

    文件类型 对于文件和目录的访问权力是根据读访问,写访问,和执行访问来定义的. 我们来看一下 ls 命令的输出结果 [root@iZ28dr6w0qvZ test]# ls -l 总用量 72 -rw- ...

  5. asp.net mvc 文件压缩下载

    压缩文件相关的类: public class ZIPCompressUtil { public static Tuple<bool, Stream> Zip(string strZipTo ...

  6. ftp多文件压缩下载

    @GetMapping(value = "/find") public String findfile(String filePath, String fileNames, Htt ...

  7. java多个文件压缩下载

    public static void zipFiles(File[] srcfile,ServletOutputStream sos){ byte[] buf=new byte[1024]; try ...

  8. UIwebview 文件的下载与保存,以及mp3文件的播放

    这里只是说说异步 单线程下载与文件的保存 以下载一个mp3文件并保存为例: -(void)loading { //设置文件下载地址 NSString *urlString = [NSString st ...

  9. 【2017-05-30】WebForm文件上传。从服务端删除文件

    用 FileUpload控件进行上传文件. <asp:FileUpload ID="FileUpload1"  runat="server" /> ...

  10. 用Spring中的ResponseEntity文件批量压缩下载

    我看了很多网上的demo,先生成ZIP压缩文件,然后再下载. 我这里是生成ZIP文件流 进行下载.(核心代码没多少,就是一些业务代码) @RequestMapping(value = "/& ...

随机推荐

  1. BZOJ3296: [USACO2011 Open] Learning Languages 并查集

    Description 农夫约翰的N(2 <= N<=10,000)头奶牛,编号为1.. N,一共会流利地使用M(1<= M <=30,000)种语言,编号从1  .. M., ...

  2. Python实现自平衡二叉树AVL

    # -*- coding: utf-8 -*- from enum import Enum #参考http://blog.csdn.net/niteip/article/details/1184069 ...

  3. python 元组查找元素返回索引

    #create a tuple tuplex = tuple("index tuple") print(tuplex) #get index of the first item w ...

  4. Django2.0 URL配置

    一.实例 先看一个例子: from django.urls import path from . import views urlpatterns = [ path('articles/2003/', ...

  5. Qt_QString::split测试

    1. #define GID_PREFIX "dr_" QString str = "dr__awedr4"; QString str1; QStringLis ...

  6. C++异常及捕获_01

    ZC: Win7x64 + qt-opensource-windows-x86-msvc2010_opengl-5.3.2.exe 1. class AA { public: void A() { & ...

  7. C89_一些函数

    C89 string.h 中的函数: 复制函数 memcpy memmove strcpy strncpy 串接函数 strcat strncat 比较函数 memcmp strcmp strcoll ...

  8. Cglib方法实现动态代理

    除了使用JDK方式产生动态代理外,Java还给我们提供了另外一种产生动态代理的方法,那就是使用cglib. cglib是这样实现动态代理的: · ①.针对类来实现代理 · ②对指定目标类产生一个子类 ...

  9. Codeforces D - The Child and Zoo

    D - The Child and Zoo 思路: 并查集+贪心 每条边的权值可以用min(a[u],a[v])来表示,然后按边的权值从大到小排序 然后用并查集从大的边开始合并,因为你要合并的这两个联 ...

  10. HTML表单组件

    HTML表单组件 一.说明 form标签里面的东西 二.效果图 三.代码 <!DOCTYPE html> <html> <head> <title>Fo ...