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 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. int processedBytes = 0;
  17. byte[] buffer = new byte[chunkSize];
  18. int bytesRemaining = length;
  19. int bytesToRead = chunkSize;
  20. do
  21. {
  22. if (chunkSize > bytesRemaining)
  23. {
  24. bytesToRead = bytesRemaining;
  25. }
  26. processedBytes = stream.Read(buffer, 0, bytesToRead);
  27. if (processedBytes > 0)
  28. {
  29. response.OutputStream.Write(buffer, 0, processedBytes);
  30. // Flush the response
  31. if (flush)
  32. {
  33. response.Flush();
  34. }
  35. // Clear the buffer
  36. Array.Clear(buffer, 0, chunkSize);
  37. // decrement the total bytes remaining to process
  38. bytesRemaining -= processedBytes;
  39. }
  40. }
  41. while (processedBytes > 0 && bytesRemaining > 0);
  42. }
  43. catch (Exception ex)
  44. {
  45. // Don't worry about it. Just leave
  46. }
  47. finally
  48. {
  49. // dispose of file stream
  50. stream?.Dispose();
  51. }
  52. }
  53. }
  54. }