code_junkie

Best way to handle a large download site?

Nov 13th, 2011
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. Stream iStream = null;
  2.  
  3. // Buffer to read 10K bytes in chunk:
  4. byte[] buffer = new Byte[10000];
  5.  
  6. // Length of the file:
  7. int length;
  8.  
  9. // Total bytes to read:
  10. long dataToRead;
  11.  
  12. if (File.Exists(localfilename))
  13. {
  14. try
  15. {
  16. // Open the file.
  17. iStream = new System.IO.FileStream(localfilename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
  18.  
  19. // Total bytes to read:
  20. dataToRead = iStream.Length;
  21.  
  22. context.Response.Clear();
  23. context.Response.Buffer = false;
  24. context.Response.ContentType = "application/octet-stream";
  25. Int64 fileLength = iStream.Length;
  26. context.Response.AddHeader("Content-Length", fileLength.ToString());
  27. context.Response.AddHeader("Content-Disposition", "attachment; filename=" + originalFilename);
  28.  
  29. // Read the bytes.
  30. while (dataToRead > 0)
  31. {
  32. // Verify that the client is connected.
  33. if (context.Response.IsClientConnected)
  34. {
  35. // Read the data in buffer.
  36. length = iStream.Read(buffer, 0, 10000);
  37.  
  38. // Write the data to the current output stream.
  39. context.Response.OutputStream.Write(buffer, 0, length);
  40.  
  41. // Flush the data to the HTML output.
  42. context.Response.Flush();
  43.  
  44. buffer = new Byte[10000];
  45. dataToRead = dataToRead - length;
  46. }
  47. else
  48. {
  49. //prevent infinite loop if user disconnects
  50. dataToRead = -1;
  51. }
  52. }
  53. iStream.Close();
  54. iStream.Dispose();
  55. }
  56. catch (Exception ex)
  57. {
  58. if (iStream != null)
  59. {
  60. iStream.Close();
  61. iStream.Dispose();
  62. }
  63. if (ex.Message.Contains("The remote host closed the connection"))
  64. {
  65. context.Server.ClearError();
  66. context.Trace.Warn("GetFile", "The remote host closed the connection");
  67. }
  68. else
  69. {
  70. context.Trace.Warn("IHttpHandler", "DownloadFile: - Error occurred");
  71. context.Trace.Warn("IHttpHandler", "DownloadFile: - Exception", ex);
  72. }
  73. context.Response.Redirect("default.aspx");
  74. }
  75. }
Add Comment
Please, Sign In to add comment