|
using System ;
using System.IO ;
using System.Web ;
using System.Text ;
namespace Matthew.Utility
{
public class FileHandler : IHttpHandler {
private const int RD_BUFFER_SIZE = 4*1024 ;
private HttpResponse Response ;
private HttpRequest Request ;
// State for Async read
public class StateObject {
public byte[] bs ;
public FileStream fs ;
}
public void ProcessRequest(HttpContext ctx) {
Response = ctx.Response ;
Request = ctx.Request ;
String Filename = Request.FilePath ;
if ( Filename != null ) {
Filename = Request.MapPath(Filename) ;
FileStream fs = null ;
try {
fs = File.Open(Filename , FileMode.Open, FileAccess.Read, FileShare.Read) ;
}
catch ( FileNotFoundException ) {
Response.Write("<html><body><h2>File <i>" + Request.FilePath + "</i> not exists!</h2></body></html>" ) ;
return ;
}
StateObject stateObject = new StateObject() ;
stateObject.fs = fs ;
stateObject.bs = new byte[RD_BUFFER_SIZE] ;
// Set the content type as the browser need to know how to display the content bases on its type
Response.ContentType = "Text/plain" ;
// Begin Async file read
fs.BeginRead( stateObject.bs, 0, RD_BUFFER_SIZE, new AsyncCallback(this.ReadCallback), stateObject );
}
} // void ProcessRequest(HttpContext ctx)
public bool IsReusable { get { return true ; } }
public void ReadCallback(IAsyncResult asyncResult) {
StateObject stateObject = (StateObject) asyncResult.AsyncState;
FileStream fs = stateObject.fs;//(Stream) asyncResult.AsyncObject;
int bytesRead = fs.EndRead(asyncResult);
// Stream only return zero (0) at the end of the stream
if ( bytesRead != 0 ) {
Response.BinaryWrite(stateObject.bs) ;
fs.BeginRead( stateObject.bs, 0, RD_BUFFER_SIZE,
new AsyncCallback(this.ReadCallback), stateObject );
}
else {
fs.Close() ;
}
}
} // Class
} // namespace
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
I am always interested in finding innovative ways for building better applications and founded a technology company since 2003. Welcome to exchange any idea with you and if I am not too busy before deadline of projects, I will reply your emails. Also, if you willing to pay for consulting works and customized software development, you can leave me message.