Search code examples
c#visual-studiosystem.io.packaging

creating Zip file on the Download folder of User profile fails


I am trying to make a zip file and download on the Download Folder of the User profile

public void CreateZipFile(string tempFolderPath, string zipFilePath, string zipFileName)
{     
  using (Package zip = Package.Open(zipFilePath, FileMode.Create))
  {
      foreach (string file in Directory.GetFiles(tempFolderPath))
      {
          if (Path.GetExtension(file).ToUpper() != ".ZIP")
          {
              string zipPartUri = $"/{Uri.UnescapeDataString(Path.GetFileName(file))}";

              Uri partUri = PackUriHelper.CreatePartUri(new Uri(zipPartUri, UriKind.Relative));
              PackagePart part = zip.CreatePart(partUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Normal);

              using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
              {
                  using (Stream zipPartStream = part.GetStream())
                  {
                      fileStream.CopyTo(zipPartStream);
                  }
              }
          }

      }
  }

  try
  {
      HttpContext.Current.Response.Clear();
      HttpContext.Current.Response.ContentType = "application/zip";
      HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + zipFileName);
      HttpContext.Current.Response.TransmitFile(zipFilePath);
      HttpContext.Current.Response.Flush();
  }
  catch (Exception ex)
  {
      // Log the exception (optional)
      Console.WriteLine("Error sending ZIP file: " + ex.Message);
  }
  finally
  {
      
      HttpContext.Current.ApplicationInstance.CompleteRequest(); // Graceful request termination
  }

}

zipFileName = "GroupFiles.zip" zipFilePath = C:\Temp\1\GroupedExcelFiles.zip

The zip file is created on the C:\Temp\1\ , but it can not transfer it to the download Folder. Actually it finishes this line

HttpContext.Current.ApplicationInstance.CompleteRequest(); // Graceful request termination

and starts returning the parent methods. but on the last one it gives error, which is on the localhost enter image description here

how can I check the problem? ps: I am using .net framework 4.0 and System.IO.Packaging; for making zip file


Solution

  • I found it as was in the UpdatePanel, I added this code into the Page_Load

    ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page); scriptManager.RegisterPostBackControl(this.btnZip);