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.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using Microsoft.AspNetCore.Http;
  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 async static Task StreamToOutput(HttpResponse response, bool flush, Stream stream, int length, int chunkSize)
  14. {
  15. try
  16. {
  17. int processedBytes = 0;
  18. byte[] buffer = new byte[chunkSize];
  19. int bytesRemaining = length;
  20. int bytesToRead = chunkSize;
  21. do
  22. {
  23. if (chunkSize > bytesRemaining)
  24. {
  25. bytesToRead = bytesRemaining;
  26. }
  27. processedBytes = stream.Read(buffer, 0, bytesToRead);
  28. if (processedBytes > 0)
  29. {
  30. await response.Body.WriteAsync(buffer, 0, processedBytes);
  31. // Flush the response
  32. if (flush)
  33. {
  34. await response.Body.FlushAsync();
  35. }
  36. // Clear the buffer
  37. Array.Clear(buffer, 0, chunkSize);
  38. // decrement the total bytes remaining to process
  39. bytesRemaining -= processedBytes;
  40. }
  41. }
  42. while (processedBytes > 0 && bytesRemaining > 0);
  43. }
  44. catch (Exception)
  45. {
  46. // Don't worry about it. Just leave
  47. await response.Body.FlushAsync();
  48. }
  49. finally
  50. {
  51. await response.Body.FlushAsync();
  52. // dispose of file stream
  53. stream?.Dispose();
  54. }
  55. }
  56. }
  57. }