応答ストリームに書き込むときに、なぜコンテンツが破損しています

StackOverflow https://stackoverflow.com/questions/1724081

質問

私は応答ストリームに書き出すためにしようとしている - しかし、それは失敗している、それは

...何とかデータを破損さ

私はこのために「WriteFile関数」を使用することはできませんので、HttpWebResponseのをどこか別の場所に保存されたストリームを書くことができるようにしたい、プラス私はいくつかの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();
        }
    }

事前に乾杯

役に立ちましたか?

解決

あなたは文字ではなく、バイトを書いているので。キャラクターは間違いなくバイトではありません。それはエンコードする必要があり、あなたの「腐敗」は出番つまり、代わりにこのようにそれを実行します。

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();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top