Created
September 6, 2012 16:42
-
-
Save wwb/3658346 to your computer and use it in GitHub Desktop.
Simple file IHttpHandler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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