using System;
using System.Globalization;
using System.IO;
using System.Web;
namespace VHelms.Web.Filemanager
{
public class HttpDownload : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
if (!string.IsNullOrEmpty(context.Request["File"]))
{
string fileName = context.Request["File"];
DownloadFile(fileName, context);
}
else
{
throw new ArgumentException("The File-ID is not available anymore. Please reload the page and try again.");
}
}
catch (Exception ex)
{
context.Response.ContentType = "text/plain";
context.Response.Write(string.Format("Error:\r\n{0}", ex));
}
}
public bool IsReusable
{
get { return true; }
}
///
///
///
///
///
private static void DownloadFile(string filepath, HttpContext context)
{
HttpResponse response = context.Response;
// Buffer to read 10K bytes in chunk:
var buffer = new Byte[10000];
// Identify the file name.
string filename = Path.GetFileName(filepath);
string appPath = context.Request.PhysicalApplicationPath;
string completeFilePath = appPath + filename;
FileStream fileStream = null;
try
{
// Open the file.
fileStream = new FileStream(completeFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
// Total bytes to read:
long dataToRead = fileStream.Length;
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
response.AddHeader("Content-Length", fileStream.Length.ToString());
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (response.IsClientConnected)
{
// Read the data in buffer.
int length = fileStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
response.ContentType = "text/plain";
response.Write(string.Format("Error:\r\n{0}", ex));
//Response.Write("Error : " + ex.Message);
}
finally
{
if (fileStream != null)
{
//Close the file.
fileStream.Close();
}
// delete tmp file, if the file is stored in the temp directory
if (filepath.StartsWith(Path.GetTempPath()))
{
// delete temp file
var tempFile = new FileInfo(filepath);
tempFile.Delete();
}
}
}
}
}