The next generation of the Teknik Services. Written in ASP.NET. Fork for blog tags.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ResponseHelper.cs 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using Org.BouncyCastle.Crypto;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Web;
  9. namespace Teknik.Utilities
  10. {
  11. public static class ResponseHelper
  12. {
  13. public static void StreamToOutput(HttpResponseBase response, bool flush, Stream stream, int length, int chunkSize)
  14. {
  15. try
  16. {
  17. if (flush)
  18. {
  19. // If the client isn't here, just quit early
  20. if (!response.IsClientConnected)
  21. {
  22. return;
  23. }
  24. response.Flush();
  25. }
  26. int curByte = 0;
  27. int processedBytes = 0;
  28. byte[] buffer = new byte[chunkSize];
  29. int bytesRemaining = length;
  30. int bytesToRead = chunkSize;
  31. do
  32. {
  33. if (chunkSize > bytesRemaining)
  34. {
  35. bytesToRead = bytesRemaining;
  36. }
  37. processedBytes = stream.Read(buffer, 0, bytesToRead);
  38. if (processedBytes > 0)
  39. {
  40. // If the client isn't here, just quit early
  41. if (!response.IsClientConnected)
  42. {
  43. return;
  44. }
  45. response.OutputStream.Write(buffer, 0, processedBytes);
  46. // Clear the buffer
  47. Array.Clear(buffer, 0, chunkSize);
  48. // Flush the response
  49. if (flush)
  50. {
  51. // If the client isn't here, just quit early
  52. if (!response.IsClientConnected)
  53. {
  54. return;
  55. }
  56. //response.OutputStream.Write(buffer, 0, 1);
  57. response.Flush();
  58. }
  59. }
  60. curByte += processedBytes;
  61. bytesRemaining -= processedBytes;
  62. }
  63. while (processedBytes > 0 && bytesRemaining > 0);
  64. }
  65. finally
  66. {
  67. // dispose of file stream
  68. if (stream != null)
  69. {
  70. stream.Dispose();
  71. }
  72. }
  73. }
  74. }
  75. }