0

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

我希望能够将存储在其他地方的流写入 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();
        }
    }

提前喝彩

4

1 回答 1

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();
}
于 2009-11-12T17:49:33.177 回答