webform生成rar文件并下载

2019-04-15 16:31发布

 protected void btnRar_Click(object sender, EventArgs e)
        {
            try
            {
                string path = Server.MapPath("/");
                string message = Rar(path + @"/uploads", @"pic/*.jpg", "", "tupian");
                string filePath = path + @"/uploads/tupian.rar";
                System.IO.FileInfo file = new System.IO.FileInfo(filePath);
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name)); //解决中文文件名乱码   
                Response.AddHeader("Content-length", file.Length.ToString());
                //Response.ContentType = "appliction/octet-stream";
                Response.WriteFile(file.FullName);
                Response.End();
            }
            catch (Exception ex)
            {
                Page.RegisterStartupScript("key", "");
            }
           
        }
        string Rar(string workDir, string sourceDir, string destDir, string destFileName)
        {
            string error = string.Empty;
            Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(@"Applications/WinRAR.exe/Shell/Open/Command");
            string rarExeFile = regKey.GetValue("").ToString().Substring(1, regKey.GetValue("").ToString().Length - 7);
            regKey.Close();
            System.Diagnostics.ProcessStartInfo pInfo = new System.Diagnostics.ProcessStartInfo();
            pInfo.FileName = rarExeFile;
            pInfo.Arguments = string.Format("a  -rr {0}.rar {1}", destFileName, sourceDir);
            pInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            pInfo.WorkingDirectory = workDir;
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo = pInfo;
            process.Start();
            error = "压缩成功";
            return error;         } ==============================================