Skip to content

Instantly share code, notes, and snippets.

@wwb
Created September 6, 2012 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wwb/3658346 to your computer and use it in GitHub Desktop.
Save wwb/3658346 to your computer and use it in GitHub Desktop.
Simple file IHttpHandler
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Collections.Generic;
public class FileHandler : IHttpHandler
{
public FileHandler() { }
#region IHttpHandler Members
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
string fn = getFileName(context);
if (!File.Exists(fn))
{
throw new HttpException(404, "File Not Found");
}
else
{
FileInfo fi=new FileInfo(fn);
context.Response.ContentType = getContentType(fi.Extension);
context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fi.Name));
context.Response.WriteFile(fn);
context.Response.End();
}
}
private string getContentType(string ext)
{
string ret = null;
switch (ext)
{
case "doc":
ret = "application/msword";
break;
case "xls":
ret="application/vnd.ms-excel";
break;
case "ppt":
ret = "application/vnd.ms-powerpoint";
break;
case "zip":
ret = "application/zip";
break;
case "txt":
ret = "text/plain";
break;
case "html":
case "htm":
ret = "text/html";
break;
default:
ret = "application/octet-stream";
break;
}
return ret;
}
private string getFileName(HttpContext context)
{
Stack<string> ss = new Stack<string>(context.Request.Url.Segments);
string tmp = ss.Pop();
tmp = tmp.Substring(0, tmp.Length - 5);
return context.Server.MapPath(string.Format("~/App_Data/{0}", tmp));
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment