2009-11-12 68 views
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

因爲你在寫字符而不是字節。一個字符絕對不是一個字節;它必須被編碼,這就是你的「腐敗」進來的地方。這樣做,而不是:

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

DOH!這是一個漫長的一天:) – AwkwardCoder 2009-11-12 17:50:38

+0

黨,打我。例如+1。 – 2009-11-12 17:50:39

相關問題