1. Read your file and store in memory stream.
2. Zip the stream and allow users to to download the zipped stream only.
U can use Open Source SharpzipLib for zipping it:
private MemoryStream GetMemoryStream(string filepath, out Exception e)
{
e = null;
MemoryStream dest = new MemoryStream();
try
{
using (Stream source = File.OpenRead(filepath))
{
dest.SetLength(source.Length);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
{
dest.Write(buffer, 0, bytesRead);
}
dest.Flush();
dest.Position = 0;
return dest;
}
}
catch (Exception ex)
{
e = new Exception("GetMemoryStream : " + ex.ToString());
return (MemoryStream)null;
}
}
public byte[] ReadToEnd(Stream stream)
{
long originalPosition = 0;
if (stream.CanSeek)
{
originalPosition = stream.Position;
stream.Position = 0;
}
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
if (stream.CanSeek)
{
stream.Position = originalPosition;
}
}
}
private byte[] ZipToByteArray(MemoryStream memStreamIn, string zipEntryName, string password)
{
MemoryStream outputMemStream = new MemoryStream();
ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);
zipStream.Password = password;
zipStream.SetLevel(3);
ZipEntry newEntry = new ZipEntry(zipEntryName);
newEntry.DateTime = DateTime.Now;
zipStream.PutNextEntry(newEntry);
StreamUtils.Copy(memStreamIn, zipStream, new byte[4096]);
zipStream.CloseEntry();
zipStream.IsStreamOwner = false;
zipStream.Close();
outputMemStream.Flush();
outputMemStream.Position = 0;
return ReadToEnd(outputMemStream);
}
And finally the download method:
void Download(string fileName, byte[] data)
{
try
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer= true;
response.AddHeader("Content-Disposition","attachment;filename=\"" + fileName + "\"");
response.BinaryWrite(data);
response.End();
}
catch(Exception ex)
{
}
}