C# 在服务器生成文件/文件夹并压缩下载到本地

有一个需求,是根据多个模板文件生成固定格式的文件与文件夹结构,实现较简单,做一下记录:

首先创建需要的树形文件夹

    //创建学科目录
    CreateDir(name_abbr);
    protected void CreateDir(string name_abbr)
    {
        string subject_path = Base_Dir + "/" + name_abbr;
        if (!Directory.Exists(subject_path))
            Directory.CreateDirectory(subject_path);
        string subject_gb_path = subject_path + "/gb";
        if (!Directory.Exists(subject_gb_path))
            Directory.CreateDirectory(subject_gb_path);
        string subject_gb_SearchBar_path = subject_gb_path + "/SearchBar";
        if (!Directory.Exists(subject_gb_SearchBar_path))
            Directory.CreateDirectory(subject_gb_SearchBar_path);
    }

创建文件:

string Base_Dir = @System.AppDomain.CurrentDomain.BaseDirectory + @"DownloadFiles"; 
string filePath = Base_Dir + "/" + name_abbr+"/"+ fileName + ".xml";
string txt = "写入文本的内容";
System.IO.File.WriteAllText(filePath, txt, Encoding.UTF8);

压缩文件与文件夹:


压缩学科文件夹生成学科压缩包 name_abbr.zip
string name_abbr = "计算机科学";
string Base_Dir = @System.AppDomain.CurrentDomain.BaseDirectory + @"DownloadFiles";
string sourceFilePath = Base_Dir + "/" + name_abbr;
string destinationZipFilePath = Base_Dir + "/" + name_abbr + ".zip";
ZipHelper.CreateZip(sourceFilePath, destinationZipFilePath);

 public class ZipHelper
  {
    /// <summary>
    /// 压缩文件
    /// </summary>
    /// <param name="sourceFilePath">待拷贝文件或文件夹 绝对路径</param>
    /// <param name="destinationZipFilePath"> 生成zip文件的绝对路径 </param>
    public static void CreateZip(string sourceFilePath, string destinationZipFilePath)
    {
      if (sourceFilePath[sourceFilePath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
        sourceFilePath += System.IO.Path.DirectorySeparatorChar;

      ZipOutputStream zipStream = new ZipOutputStream(File.Create(destinationZipFilePath));
      zipStream.SetLevel(6);  // 压缩级别 0-9
      CreateZipFiles(sourceFilePath, zipStream, sourceFilePath);

      zipStream.Finish();
      zipStream.Close();
    }

    /// <summary>
    /// 递归压缩文件
    /// </summary>
    /// <param name="sourceFilePath">待压缩的文件或文件夹路径</param>
    /// <param name="zipStream">打包结果的zip文件路径(类似 D:\WorkSpace\a.zip),全路径包括文件名和.zip扩展名</param>
    /// <param name="staticFile"></param>
    private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream, string staticFile)
    {
      Crc32 crc = new Crc32();
      string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
      foreach (string file in filesArray)
      {
        if (Directory.Exists(file))                     //如果当前是文件夹,递归
        {
          CreateZipFiles(file, zipStream, staticFile);
        }

        else                                            //如果是文件,开始压缩
        {
          FileStream fileStream = File.OpenRead(file);

          byte[] buffer = new byte[fileStream.Length];
          fileStream.Read(buffer, 0, buffer.Length);
          string tempFile = file.Substring(staticFile.LastIndexOf("\\") + 1);
          ZipEntry entry = new ZipEntry(tempFile);

          entry.DateTime = DateTime.Now;
          entry.Size = fileStream.Length;
          fileStream.Close();
          crc.Reset();
          crc.Update(buffer);
          entry.Crc = crc.Value;
          zipStream.PutNextEntry(entry);

          zipStream.Write(buffer, 0, buffer.Length);
        }
      }
    }
  }

从服务器上下载压缩包保存至本地:

string Base_Dir = @System.AppDomain.CurrentDomain.BaseDirectory + @"DownloadFiles";
this.OutPutZipFile(Request.RequestContext.HttpContext.ApplicationInstance.Context,  "target.zip");//调用方式
protected void OutPutZipFile(HttpContext context, string fileName)
    {
        string filePath = Base_Dir + "/" + fileName ;
        FileStream fs = new FileStream(filePath, FileMode.Open);//使用字节流的方式打开
        byte[] bytes = new byte[(int)fs.Length];
        fs.Read(bytes, 0, bytes.Length);
        fs.Close();
        context.Response.ContentType = "application/octet-stream";
        context.Response.AddHeader("Title", fileName);
        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
        context.Response.BinaryWrite(bytes);
        context.Response.Flush();
        context.Response.End();
    }

删除文件以及文件夹

string Base_Dir = @System.AppDomain.CurrentDomain.BaseDirectory + @"DownloadFiles";    
string foladerPath = Base_Dir + "\\" + "target.zip";
DeleteDirectory(Base_Dir, foladerPath);//删除文件
DeleteDirectory(Base_Dir, foladerPath.Replace(".zip", ""));//删除文件夹



private void DeleteDirectory(string directoryPath, string fileName)
    {
      //删除文件
      for (int i = 0; i < Directory.GetFiles(directoryPath).ToList().Count; i++)
      {
        if (Directory.GetFiles(directoryPath)[i] == fileName)
        {
          File.Delete(fileName);
        }
      }
      //删除文件夹
      for (int i = 0; i < Directory.GetDirectories(directoryPath).ToList().Count; i++)
      {
        if (Directory.GetDirectories(directoryPath)[i] == fileName)
        {
          Directory.Delete(fileName, true);
        }
      }
    }

参考博客:

总结C#获取当前路径的7种方法

C# 删除文件以及文件夹

C#的几种压缩文件方法

C#从服务器下载文件的四种方式

C#打包文件夹成zip格式(包括文件夹和子文件夹下的所有文件)

c#之从服务器下载压缩包,并解压

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值