为什么写入响应流时内容被破坏

时间:2009-11-12 17:46:24

标签: c# .net httphandler httpwebresponse

我正在尝试写出响应流 - 但它失败了,它以某种方式破坏了数据......

我希望能够将存储在其他地方的流写入HttpWebResponse,所以我不能为此使用'WriteFile',而且我想为几种MIME类型执行此操作,但它对所有这些都失败 - mp3, pdf等...

 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();
        }
    }

提前干杯

1 个答案:

答案 0 :(得分:4)

因为你在写字符而不是字节。一个字符绝对不是一个字节;它必须被编码,这就是你的“腐败”所在的地方。请这样做:

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();
}