{
byte[] buffer = new byte[4096];
// the path on the server where the temp file will be created!
var tempFileName = Server.MapPath(@"TempFiles/" + Guid.NewGuid().ToString() + ".zip");
var zipOutputStream = new ZipOutputStream(File.Create(tempFileName));
var filePath = String.Empty;
var fileName = String.Empty;
var readBytes = 0;
foreach(GridViewRow row in gvFiles.Rows)
{
var isChecked = (row.FindControl("chkSelect") as CheckBox).Checked;
if (!isChecked) continue;
filePath = (row.FindControl("lblFilePath") as Label).Text;
fileName = (row.FindControl("lblFileName") as Label).Text;
var zipEntry = new ZipEntry(fileName);
zipOutputStream.PutNextEntry(zipEntry);
using(var fs = File.OpenRead(filePath))
{
do
{
readBytes = fs.Read(buffer, 0, buffer.Length);
zipOutputStream.Write(buffer,0,readBytes);
} while (readBytes > 0);
}
}
if (zipOutputStream.Length == 0)
{
lblMessage.Text = "Please select at least one file!";
return;
}
zipOutputStream.Finish();
zipOutputStream.Close();
Response.ContentType = "application/x-zip-compressed";
Response.AppendHeader("Content-Disposition", "attachment; filename=YourFile.zip");
Response.WriteFile(tempFileName);
Response.Flush();
Response.Close();
// delete the temp file
if(File.Exists(tempFileName))
File.Delete(tempFileName);
}
No comments:
Post a Comment