The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
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.6KB

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