giammin

ASP.NET download/open file/stream in browser

Apr 2nd, 2013
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.57 KB | None | 0 0
  1. //for very big files use  HttpReponse.TransmitFile()  http://msdn.microsoft.com/en-us/library/12s31dhy(v=vs.80).aspx
  2.  
  3. protected void SendFileToResponse(string physicalPath, string fileName)
  4. {
  5.     //se si presenta il problema della cache del browser si può appendere una querystring casuale in modo da far ricaricare
  6.     CurrentContext.Response.ContentType = FileContentType; //"application/pdf", "image/png"
  7.     string tmp = "inline";
  8.     if (CurrentContext.Request.QueryString["d"] == "1")
  9.     {
  10.         tmp = "attachment";
  11.     }
  12.     CurrentContext.Response.AddHeader("Content-Disposition", string.Format("{1}; filename={0}", fileName, tmp));
  13.    
  14.     using (Stream s = new FileStream(physicalPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  15.     {
  16.         s.CopyTo(CurrentContext.Response.OutputStream);
  17.     }
  18.     if (CurrentContext.Response.IsClientConnected)
  19.     {
  20.         CurrentContext.Response.Flush();
  21.     }
  22. }
  23.  
  24. private void SendStreamToResponse(MemoryStream stream, string fileName)
  25. {
  26.     //se si presenta il problema della cache del browser si può appendere una querystring casuale in modo da far ricaricare
  27.     CurrentContext.Response.ContentType = FileContentType;  //"application/pdf", "image/png"
  28.     string tmp = "inline";
  29.     if (CurrentContext.Request.QueryString["d"] == "1")
  30.     {
  31.         tmp = "attachment";
  32.     }
  33.     CurrentContext.Response.AddHeader("Content-Disposition", string.Format("{1}; filename={0}", fileName, tmp));
  34.        
  35.         //stream is disposed by method caller
  36.     stream.WriteTo(CurrentContext.Response.OutputStream);
  37.     if (CurrentContext.Response.IsClientConnected)
  38.     {
  39.         CurrentContext.Response.Flush();
  40.     }
  41. }
Add Comment
Please, Sign In to add comment