I'm trying to write out to the response stream - but it is failing, it is corrupting the data somehow...
I want to be able to write a stream stored somewhere else to the HttpWebResponse so I can't use 'WriteFile' for this, plus I want to do this for several MIME types but it fails for all of them - mp3, pdf etc...
public void ProcessRequest(HttpContext context)
{
var httpResponse = context.Response;
httpResponse.Clear();
httpResponse.BufferOutput = true;
httpResponse.StatusCode = 200;
using (var reader = new FileStream(Path.Combine(context.Request.PhysicalApplicationPath, "Data\\test.pdf"), FileMode.Open, FileAccess.Read, FileShare.Read))
{
开发者_高级运维 var buffer = new byte[reader.Length];
reader.Read(buffer, 0, buffer.Length);
httpResponse.ContentType = "application/pdf";
httpResponse.Write(Encoding.Default.GetChars(buffer, 0, buffer.Length), 0, buffer.Length);
httpResponse.End();
}
}
Cheers in advance
Because you're writing characters, not bytes. A character is definitely not a byte; it has to be encoded, and that is where your "corruption" comes in. Do it like this instead:
using (var reader = new FileStream(Path.Combine(context.Request.PhysicalApplicationPath, "Data\\test.pdf"), FileMode.Open, FileAccess.Read, FileShare.Read))
{
var buffer = new byte[reader.Length];
reader.Read(buffer, 0, buffer.Length);
httpResponse.ContentType = "application/pdf";
httpResponse.BinaryWrite(buffer);
httpResponse.End();
}
精彩评论