1
0
mirror of https://git.teknik.io/Teknikode/Teknik.git synced 2023-08-02 14:16:22 +02:00
Teknik/Utilities/ResponseHelper.cs

53 lines
1.5 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Http;
using System;
2017-02-10 07:34:50 +01:00
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Teknik.Utilities
{
public static class ResponseHelper
{
public async static Task StreamToOutput(HttpResponse response, bool flush, Stream stream, int length, int chunkSize)
2017-02-10 07:34:50 +01:00
{
2022-05-22 03:55:22 +02:00
var bufferSize = chunkSize;
if (length < chunkSize)
bufferSize = length;
Memory<byte> buffer = new byte[bufferSize];
2017-02-10 07:34:50 +01:00
try
{
int processedBytes;
2017-02-10 07:34:50 +01:00
do
{
2022-05-21 18:29:24 +02:00
processedBytes = await stream.ReadAsync(buffer);
2017-02-10 07:34:50 +01:00
if (processedBytes > 0)
{
2022-05-21 18:29:24 +02:00
await response.Body.WriteAsync(buffer.Slice(0, processedBytes));
2017-04-09 09:16:24 +02:00
2018-01-29 00:08:32 +01:00
// Flush the response
if (flush)
{
await response.Body.FlushAsync();
2018-01-29 00:08:32 +01:00
}
2017-02-10 07:34:50 +01:00
}
}
2022-05-21 18:29:24 +02:00
while (processedBytes > 0);
2017-02-10 07:34:50 +01:00
}
catch (Exception ex)
{
// Don't worry about it. Just leave
}
2017-02-10 07:34:50 +01:00
finally
{
await response.Body.FlushAsync();
2022-05-21 18:29:24 +02:00
2017-02-10 07:34:50 +01:00
// dispose of file stream
2018-01-29 00:08:32 +01:00
stream?.Dispose();
2017-02-10 07:34:50 +01:00
}
}
}
}