| | 1 | | // src/CSharp/Kestrun.Net/KrHttp.Downloads.cs |
| | 2 | | using System.Net.Http.Headers; |
| | 3 | |
|
| | 4 | | namespace Kestrun.Client; |
| | 5 | |
|
| | 6 | | /// <summary> |
| | 7 | | /// Helper methods for common HTTP download scenarios. |
| | 8 | | /// </summary> |
| | 9 | | public static class KrHttpDownloads |
| | 10 | | { |
| | 11 | | /// <summary> |
| | 12 | | /// Streams an HTTP response body to a file, supporting very large payloads and optional resume. |
| | 13 | | /// Returns the final file length in bytes. |
| | 14 | | /// </summary> |
| | 15 | | public static async Task<long> DownloadToFileAsync( |
| | 16 | | HttpClient client, |
| | 17 | | HttpRequestMessage request, |
| | 18 | | string filePath, |
| | 19 | | bool resume = false, |
| | 20 | | int bufferBytes = 1 << 20, // 1 MiB |
| | 21 | | CancellationToken cancellationToken = default) |
| | 22 | | { |
| 0 | 23 | | ArgumentNullException.ThrowIfNull(client); |
| 0 | 24 | | ArgumentNullException.ThrowIfNull(request); |
| 0 | 25 | | if (string.IsNullOrWhiteSpace(filePath)) |
| | 26 | | { |
| 0 | 27 | | throw new ArgumentNullException(nameof(filePath)); |
| | 28 | | } |
| | 29 | |
|
| 0 | 30 | | if (bufferBytes < 81920) |
| | 31 | | { |
| 0 | 32 | | bufferBytes = 81920; |
| | 33 | | } |
| | 34 | |
|
| 0 | 35 | | var mode = FileMode.Create; |
| 0 | 36 | | if (resume && File.Exists(filePath)) |
| | 37 | | { |
| | 38 | | // Resume support: if file exists, set Range header and append to file. |
| 0 | 39 | | var existing = new FileInfo(filePath).Length; |
| 0 | 40 | | if (existing > 0) |
| | 41 | | { |
| 0 | 42 | | request.Headers.Range = new RangeHeaderValue(existing, null); |
| 0 | 43 | | mode = FileMode.Append; |
| | 44 | | } |
| | 45 | | } |
| | 46 | |
|
| 0 | 47 | | using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken |
| 0 | 48 | | .ConfigureAwait(false); |
| 0 | 49 | | _ = response.EnsureSuccessStatusCode(); |
| | 50 | |
|
| 0 | 51 | | await using var source = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); |
| 0 | 52 | | _ = Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(filePath))!); |
| 0 | 53 | | await using var target = new FileStream( |
| 0 | 54 | | filePath, |
| 0 | 55 | | mode, |
| 0 | 56 | | FileAccess.Write, |
| 0 | 57 | | FileShare.None, |
| 0 | 58 | | bufferBytes, |
| 0 | 59 | | FileOptions.Asynchronous | FileOptions.SequentialScan); |
| | 60 | |
|
| 0 | 61 | | await source.CopyToAsync(target, bufferBytes, cancellationToken).ConfigureAwait(false); |
| | 62 | |
|
| 0 | 63 | | await target.FlushAsync(cancellationToken).ConfigureAwait(false); |
| 0 | 64 | | return new FileInfo(filePath).Length; |
| 0 | 65 | | } |
| | 66 | | } |