### Example Download Event Handlers Source: https://github.com/bezzad/downloader/blob/master/README.md Implementations for handling download start, progress, and completion events. Always check for errors and cancellations in the completion handler. ```csharp void OnDownloadStarted(object? sender, DownloadStartedEventArgs e) => Console.WriteLine($"Started '{e.FileName}' ({e.TotalBytesToReceive} bytes)"); void OnDownloadProgressChanged(object? sender, DownloadProgressChangedEventArgs e) => Console.WriteLine($"{e.ProgressPercentage:F1}% @ {e.BytesPerSecondSpeed:F0} B/s"); void OnDownloadFileCompleted(object? sender, System.ComponentModel.AsyncCompletedEventArgs e) { if (e.Cancelled) Console.WriteLine("Download was stopped/paused by the caller."); else if (e.Error is not null) Console.WriteLine($"Download FAILED: {e.Error.Message}"); // inspect/log e.Error else Console.WriteLine("Download completed successfully."); } ``` -------------------------------- ### Example Output Location for Windows Source: https://github.com/bezzad/downloader/blob/master/README.md This is an example of the specific output path for a Windows x64 build. ```bash bin/Release/net8.0/win-x64/publish/ ``` -------------------------------- ### Basic Download Configuration Example Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Example demonstrating how to configure download settings like chunk count, parallel downloads, and maximum speed using fluent methods. ```csharp var download = DownloadBuilder.New() .WithUrl("https://example.com/file.zip") .WithDirectory(@"C:\\Downloads") .Configure(opt => { opt.ChunkCount = 8; opt.ParallelDownload = true; opt.MaximumBytesPerSecond = 2 * 1024 * 1024; // 2 MB/s }) .Build(); ``` -------------------------------- ### Complete File Downloader Example in C# Source: https://github.com/bezzad/downloader/blob/master/_autodocs/quick-start.md This example demonstrates how to set up a `FileDownloader` class with custom download configurations and event handlers for download progress and completion. It includes usage instructions. ```csharp public class FileDownloader { private readonly DownloadService _downloader; public FileDownloader() { var config = new DownloadConfiguration { ChunkCount = 8, ParallelDownload = true, ParallelCount = 4, MaxTryAgainOnFailure = 5, EnableAutoResumeDownload = true, MaximumMemoryBufferBytes = 100 * 1024 * 1024, CheckDiskSizeBeforeDownload = true, RequestConfiguration = { UserAgent = "MyApp/1.0" } }; _downloader = new DownloadService(config); _downloader.DownloadStarted += OnStarted; _downloader.DownloadProgressChanged += OnProgress; _downloader.DownloadFileCompleted += OnCompleted; } public async Task Download(string url, string filePath) { await _downloader.DownloadFileTaskAsync(url, filePath); } private void OnStarted(object s, DownloadStartedEventArgs e) { Console.WriteLine($"Downloading {e.FileName} ({e.TotalBytesToReceive / 1024 / 1024}MB)..."); } private void OnProgress(object s, DownloadProgressChangedEventArgs e) { Console.Write($"\r{e.ProgressPercentage:F1}% @ {e.BytesPerSecondSpeed / 1024 / 1024:F2}MB/s"); } private void OnCompleted(object s, AsyncCompletedEventArgs e) { Console.WriteLine(); if (e.Error != null) { Console.WriteLine($"ERROR: {e.Error.Message}"); } else if (e.Cancelled) { Console.WriteLine("Cancelled"); } else { Console.WriteLine("Complete!"); } } } // Usage: var dl = new FileDownloader(); await dl.Download("https://example.com/file.zip", @"C:\\Downloads\\file.zip"); ``` -------------------------------- ### Chunking Example with ChunkHub Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-advanced.md Demonstrates how to use the ChunkHub to divide a file into chunks and print the details of each chunk. This example shows the practical application of the SetFileChunks method. ```csharp var package = new DownloadPackage { TotalFileSize = 10_000_000 }; // 10 MB var hub = new ChunkHub(new DownloadConfiguration { ChunkCount = 4 }); hub.SetFileChunks(package); foreach (var chunk in package.Chunks) { Console.WriteLine($"Chunk {chunk.Id}: {chunk.Start}-{chunk.End} ({chunk.Length} bytes)"); } ``` -------------------------------- ### Get Remote File Info Example Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Demonstrates how to retrieve and use remote file information, checking for resumability and file size. ```csharp var info = await RemoteFileResolver.GetFileInfoAsync("https://example.com/video.mp4"); if (info.SupportsRange) { Console.WriteLine("Download is resumable"); } else { Console.WriteLine("Download must complete in one session"); } if (info.FileSize > 0) { Console.WriteLine($"Size: {info.FileSize / (1024*1024):F1} MB"); } else { Console.WriteLine("Server did not advertise file size"); } ``` -------------------------------- ### Custom HttpClient Configuration Example Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Example showing how to provide a custom HttpClient with specific HttpMessageHandler settings like connection limits. ```csharp var download = DownloadBuilder.New() .WithUrl("https://example.com/file.zip") .WithDirectory(@"C:\\Downloads") .WithHttpClient(() => { var handler = new SocketsHttpHandler { MaxConnectionsPerServer = 500 }; var client = new HttpClient(handler); client.Timeout = TimeSpan.FromSeconds(60); return client; }) .Build(); ``` -------------------------------- ### Binary Serialization Example Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-advanced.md Demonstrates how to serialize a DownloadPackage to a binary file and then deserialize it back. This is useful for saving and loading package configurations. ```csharp // Save package to JSON-encoded binary var serializer = new JsonBinarySerializer(); byte[] bytes = serializer.Serialize(downloader.Package); File.WriteAllBytes("package.bin", bytes); // Load it back byte[] loaded = File.ReadAllBytes("package.bin"); var package = serializer.Deserialize(loaded); await downloader.DownloadFileTaskAsync(package); ``` -------------------------------- ### Configure Download URL and Directory Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Example of configuring a download with a URL and a target directory. Ensure the directory path is valid. ```csharp var download = DownloadBuilder.New() .WithUrl("https://example.com/file.zip") .WithDirectory(@"C:\Downloads") .Build(); ``` -------------------------------- ### SocketClient Usage Example Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-advanced.md Example demonstrating how to use SocketClient to get remote file information. Automatically handles redirects. ```csharp var request = new Request("https://example.com/download/file.zip?token=xyz"); var client = new SocketClient(config); var info = await client.GetFileInfoAsync(request, CancellationToken.None); // Automatically follows redirects (including "307 to self" cookie challenges) Console.WriteLine($"File: {info.FileName} ({info.FileSize} bytes)"); ``` -------------------------------- ### Install Downloader Package Source: https://github.com/bezzad/downloader/blob/master/_autodocs/quick-start.md Add the Downloader NuGet package to your .NET project. ```bash dotnet add package Downloader ``` -------------------------------- ### Instantiate Chunk with Byte Range Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Example of creating a Chunk instance for the first 1MB of a file. Ensure the start and end values accurately reflect the desired segment. ```csharp var chunk = new Chunk(0, 999999); // First 1MB of a file ``` -------------------------------- ### Install Downloader via NuGet Package Manager Source: https://github.com/bezzad/downloader/blob/master/README.md Use this command in the Package Manager Console to install the Downloader library. ```powershell PM> Install-Package Downloader ``` -------------------------------- ### Run Downloader Tests Source: https://github.com/bezzad/downloader/blob/master/src/CLAUDE.md Execute integration tests for the Downloader project. This command automatically starts the DummyHttpServer in-process. ```bash dotnet test src/Downloader.Test/ ``` -------------------------------- ### Example Usage of DownloadPackage Properties Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Demonstrates how to access and display properties of a DownloadPackage instance, such as received bytes, total size, and status. ```csharp var package = downloader.Package; Console.WriteLine($"Downloaded: {package.ReceivedBytesSize}/{package.TotalFileSize}"); Console.WriteLine($"Status: {package.Status}"); if (package.Status == DownloadStatus.Completed) { Console.WriteLine("File ready at: " + package.FileName); } ``` -------------------------------- ### Start Download to Directory Source: https://github.com/bezzad/downloader/blob/master/README.md Initiate a file download to a specified directory. The file will be saved with its original name within the directory. Ensure the directory exists. ```csharp DirectoryInfo path = new DirectoryInfo("Your_Path"); string url = @"https://file-examples.com/fileName.zip"; // download into "Your_Path\fileName.zip" await downloader.DownloadFileTaskAsync(url, path); ``` -------------------------------- ### Create New DownloadBuilder Instance Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Use this static method to get a new instance of the DownloadBuilder. This is the starting point for configuring a new download. ```csharp public static DownloadBuilder New() ``` -------------------------------- ### Request Constructor Example Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Illustrates creating a Request object, showing automatic percent-encoding of URL characters. ```csharp var request = new Request("https://example.com/file[name].zip"); // URL is automatically normalized: square brackets are percent-encoded ``` -------------------------------- ### Complex Download with DownloadBuilder and Event Handlers Source: https://github.com/bezzad/downloader/blob/master/README.md This example demonstrates advanced configuration, including setting a file name, custom download configuration, and attaching event handlers for progress and completion. It also shows how to stop a download. ```csharp IDownload download = DownloadBuilder.New() .WithUrl(@"https://host.com/test-file.zip") .WithDirectory(@"C:\temp") .WithFileName("test-file.zip") .WithConfiguration(new DownloadConfiguration()) .Build(); download.DownloadProgressChanged += DownloadProgressChanged; download.DownloadFileCompleted += DownloadFileCompleted; download.DownloadStarted += DownloadStarted; download.ChunkDownloadProgressChanged += ChunkDownloadProgressChanged; await download.StartAsync(); download.Stop(); // cancel current download ``` -------------------------------- ### Custom HttpMessageHandler Configuration Example Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Example demonstrating the use of a custom HttpMessageHandler with specific settings like pooled connection lifetime. ```csharp var download = DownloadBuilder.New() .WithUrl("https://example.com/file.zip") .WithDirectory(@"C:\\Downloads") .WithHttpMessageHandler(() => new SocketsHttpHandler { MaxConnectionsPerServer = 500, PooledConnectionLifetime = TimeSpan.FromMinutes(10) }) .Build(); ``` -------------------------------- ### DownloadService Main Methods Source: https://github.com/bezzad/downloader/blob/master/_autodocs/INDEX.md Lists the primary methods for controlling the download process, including starting, pausing, resuming, and canceling downloads. ```csharp // Main methods Task StartAsync(CancellationToken cancellationToken = default) void Pause() void Resume() void CancelAsync() Task CancelTaskAsync() ``` -------------------------------- ### StartAsync Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-interfaces.md Starts the download operation asynchronously. It returns a Task that resolves to a Stream of the downloaded file, or null if the file is saved directly to disk. ```APIDOC ## StartAsync(CancellationToken cancellationToken = default) ### Description Starts the download operation asynchronously. ### Method `StartAsync` ### Parameters #### Path Parameters - **cancellationToken** (CancellationToken) - Optional - Token to cancel the operation ### Returns Task - Downloaded file stream (null if saved to file) ### Example ```csharp var download = DownloadBuilder.New() .WithUrl("https://example.com/file.zip") .WithDirectory(@"C:\Downloads") .Build(); download.DownloadProgressChanged += (s, e) => { Console.WriteLine($"Progress: {e.ProgressPercentage:F1}%"); }; await download.StartAsync(); ``` ``` -------------------------------- ### Build Download with URL and File Location Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Builds an IDownload instance specifying both the URL and the exact file location. This download can then be started. ```csharp var download = DownloadBuilder.New() .WithUrl("https://example.com/file.zip") .WithFileLocation(@"C:\Downloads\file.zip") .Build(); await download.StartAsync(); ``` -------------------------------- ### Start Download with Progress Reporting Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-interfaces.md Initiates an asynchronous download operation. Subscribe to the DownloadProgressChanged event to monitor progress. The download can be cancelled using a CancellationToken. ```csharp var download = DownloadBuilder.New() .WithUrl("https://example.com/file.zip") .WithDirectory(@"C:\\Downloads") .Build(); download.DownloadProgressChanged += (s, e) => { Console.WriteLine($"Progress: {e.ProgressPercentage:F1}%"); }; await download.StartAsync(); ``` -------------------------------- ### Build Download from Existing Package Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Resumes an interrupted download using a previously saved DownloadPackage. This is useful for continuing downloads without starting from scratch. ```csharp // Resume a previously interrupted download var download = DownloadBuilder.Build(savedPackage); await download.StartAsync(); ``` -------------------------------- ### Custom Download with Error Handling (C#) Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-advanced.md Demonstrates a complete custom download process with detailed configuration and event handling for download start, progress, and completion. Includes specific error handling for configuration issues. ```csharp public async Task DownloadWithCustomHandling(string url, string filePath) { // Configuration var config = new DownloadConfiguration { ChunkCount = 8, ParallelDownload = true, ParallelCount = 4, MaxTryAgainOnFailure = 5, EnableAutoResumeDownload = true, MaximumMemoryBufferBytes = 100 * 1024 * 1024, CheckDiskSizeBeforeDownload = true, RequestConfiguration = { UserAgent = "MyApp/1.0", Proxy = null // or set proxy } }; var downloader = new DownloadService(config); // Events downloader.DownloadStarted += (s, e) => { Console.WriteLine($"Started: {e.FileName} ({e.TotalBytesToReceive / 1024 / 1024}MB)"); }; downloader.DownloadProgressChanged += (s, e) => { Console.WriteLine($"Progress: {e.ProgressPercentage:F1}% @ {e.BytesPerSecondSpeed / 1024 / 1024:F2}MB/s"); }; downloader.DownloadFileCompleted += (s, e) => { if (e.Error != null) { Console.WriteLine($"Error: {e.Error.GetType().Name}: {e.Error.Message}"); } else if (e.Cancelled) { Console.WriteLine("Cancelled"); } else { Console.WriteLine("Success"); } }; // Download try { await downloader.DownloadFileTaskAsync(url, filePath); } catch (ArgumentException ae) { Console.WriteLine($"Configuration error: {ae.Message}"); } } ``` -------------------------------- ### Resume Existing Download Package Source: https://github.com/bezzad/downloader/blob/master/README.md Use this to resume a download that was previously started and potentially interrupted, using its existing package information. ```csharp await DownloadBuilder.Build(package).StartAsync(); ``` -------------------------------- ### DownloadStartedEventArgs Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-interfaces.md Provides information about a download that has just started. It includes the file name and the total bytes to be received. ```APIDOC ## DownloadStartedEventArgs Event arguments passed when a download starts. ### Properties | Property | Type | Description | |----------|------|-------------| | FileName | string | Name of the file being downloaded | | TotalBytesToReceive | long | Total bytes that will be received | ### Constructor ```csharp public DownloadStartedEventArgs(string fileName, long totalBytes) ``` | Parameter | Type | Description | |-----------|------|-------------| | fileName | string | The file name (may be from URL or Content-Disposition header) | | totalBytes | long | Total file size in bytes (may be 0 for unknown-length downloads) | ``` -------------------------------- ### Fast and Reliable Download Configuration Source: https://github.com/bezzad/downloader/blob/master/_autodocs/README.md Configure the downloader for optimal speed and reliability. This is a recommended starting point for most download tasks. ```csharp var config = new DownloadConfiguration { ChunkCount = 8, ParallelDownload = true, ParallelCount = 4, MaxTryAgainOnFailure = 5, EnableAutoResumeDownload = true, MaximumMemoryBufferBytes = 50 * 1024 * 1024, CheckDiskSizeBeforeDownload = true }; ``` -------------------------------- ### Start Download Task Asynchronously Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-advanced.md Initiates the download process for a package. This high-level method fires all relevant events and is the underlying call for the IDownload interface when using DownloadBuilder. ```csharp public virtual async Task StartAsync(CancellationToken cancellationToken = default) ``` -------------------------------- ### Configure and Build a Download with Fluent API Source: https://github.com/bezzad/downloader/blob/master/_autodocs/quick-start.md Use the fluent builder API to configure download options such as URL, directory, chunk count, and parallel downloads. Subscribe to progress events and start the download. ```csharp var download = DownloadBuilder.New() .WithUrl("https://example.com/file.zip") .WithDirectory(@"C:\Downloads") .Configure(opt => { opt.ChunkCount = 8; opt.ParallelDownload = true; }) .Build(); download.DownloadProgressChanged += (s, e) => Console.WriteLine($"{e.ProgressPercentage:F1}%"); await download.StartAsync(); ``` -------------------------------- ### Start Download to File Source: https://github.com/bezzad/downloader/blob/master/README.md Initiate a file download to a specified path. The DownloadFileTaskAsync method completes normally even on failure; always check the DownloadFileCompleted event. ```csharp string file = @"Your_Path\fileName.zip"; string url = @"https://file-examples.com/fileName.zip"; await downloader.DownloadFileTaskAsync(url, file); ``` -------------------------------- ### ThrottledStream Usage Example Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-advanced.md Demonstrates how to set the bandwidth limit for a ThrottledStream and perform read operations. The stream will automatically pause if the read rate exceeds the specified limit. ```csharp var stream = new ThrottledStream(httpStream, MaximumBytesPerChunk); stream.MaximumBytesPerSecond = 1024 * 1024; // 1 MB/s limit byte[] buffer = new byte[4096]; int read = await stream.ReadAsync(buffer, 0, buffer.Length); // If reading too fast, stream sleeps to stay under limit ``` -------------------------------- ### Handle Download Progress Events Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-interfaces.md Example of subscribing to the DownloadProgressChanged event to display download progress, received bytes, total bytes, and download speed. This handler provides real-time feedback on the download status. ```csharp downloader.DownloadProgressChanged += (s, e) => { Console.WriteLine($"Progress: {e.ProgressPercentage:F1}% ({e.ReceivedBytesSize}/{e.TotalBytesToReceive})"); Console.WriteLine($"Speed: {e.BytesPerSecondSpeed / 1024 / 1024:F2} MB/s"); Console.WriteLine($"Active chunks: {e.ActiveChunks}"); }; ``` -------------------------------- ### Get File Info Async (Custom Configuration) Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Resolves complete file metadata using custom configuration, such as authentication headers or cookie containers. Useful for accessing protected resources. ```csharp public static async Task GetFileInfoAsync(string url, DownloadConfiguration configuration, CancellationToken cancelToken = default) ``` ```csharp var config = new DownloadConfiguration { RequestConfiguration = { Authorization = new AuthenticationHeaderValue("Bearer", "token123"), CookieContainer = new CookieContainer() } }; var fileInfo = await RemoteFileResolver.GetFileInfoAsync( "https://api.example.com/files/download?id=123", config ); if (fileInfo.FileSize > 0) { Console.WriteLine($"Will download {fileInfo.FileSize / (1024 * 1024)}MB"); } ``` -------------------------------- ### Create Chunk with Default Settings Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Creates a new chunk with default timeout (5 seconds) and an auto-generated GUID. Use when no specific byte range is initially required. ```csharp public Chunk() ``` -------------------------------- ### Get File Info Async (Default) Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Resolves complete file metadata including name, size, range support, and final address using default configuration. Handles errors by falling back to URL-derived names. ```csharp public static Task GetFileInfoAsync(string url, CancellationToken cancelToken = default) ``` ```csharp var fileInfo = await RemoteFileResolver.GetFileInfoAsync("https://example.com/download/video.mp4"); Console.WriteLine($"Name: {fileInfo.FileName}"); Console.WriteLine($"Size: {fileInfo.FileSize} bytes"); Console.WriteLine($"Supports Range: {fileInfo.SupportsRange}"); Console.WriteLine($"Final URL: {fileInfo.Address}"); ``` -------------------------------- ### Create Download Service Instance Source: https://github.com/bezzad/downloader/blob/master/README.md Instantiate the DownloadService with the specified configuration options. ```csharp var downloader = new DownloadService(downloadOpt); ``` -------------------------------- ### GetFileNameFromUrl Example Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Demonstrates extracting a file name from a URL that includes a query string. ```csharp var request = new Request("https://example.com/downloads/report.pdf?token=abc123"); Console.WriteLine(request.GetFileNameFromUrl()); // "report.pdf" ``` -------------------------------- ### Simple Download Configuration Source: https://github.com/bezzad/downloader/blob/master/README.md Create a basic download configuration with chunk count and parallel download settings. ```csharp var downloadOpt = new DownloadConfiguration() { ChunkCount = 8, // Number of file parts, default is 1 ParallelDownload = true // Download parts in parallel (default is false) }; ``` -------------------------------- ### Get HttpRequestMessage Method Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Generates an HttpRequestMessage with all configured headers, authentication, and HTTP version. ```csharp public HttpRequestMessage GetRequest() ``` -------------------------------- ### Configure Proxy and HTTPS Settings Source: https://github.com/bezzad/downloader/blob/master/_autodocs/quick-start.md Set up a WebProxy for the download requests. Note that HTTPS certificate handling is managed via HttpClientHandler configuration if needed. ```csharp var config = new DownloadConfiguration { ChunkCount = 4, RequestConfiguration = { Proxy = new WebProxy("http://proxy.company.com:8080") { UseDefaultCredentials = true }, // For self-signed certificates (not recommended for production): // Handled via HttpClientHandler configuration if needed } }; var downloader = new DownloadService(config); await downloader.DownloadFileTaskAsync(url, path); ``` -------------------------------- ### Clone Downloader Repository Source: https://github.com/bezzad/downloader/blob/master/README.md Clone the project repository and navigate into the project directory. This is the first step before building. ```bash git clone https://github.com/bezzad/downloader.git cd downloader ``` -------------------------------- ### SocketClient.SetRequestFileNameAsync Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-advanced.md Resolves the file name from the `Content-Disposition` header, URL path, or generates a GUID if none is found. ```APIDOC ## SetRequestFileNameAsync(Request request, CancellationToken cancel) ### Description Resolves the file name from `Content-Disposition` header, URL path, or generates a GUID. ### Method `async Task` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var request = new Request("https://example.com/download/file.zip"); var client = new SocketClient(config); var fileName = await client.SetRequestFileNameAsync(request, CancellationToken.None); ``` ### Response #### Success Response (200) - **string**: The resolved file name. #### Response Example ```json "file.zip" ``` ``` -------------------------------- ### Initialize DownloadService with Default Configuration Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md This constructor initializes the DownloadService using default settings. It's useful when you don't need custom configurations and want to leverage built-in defaults, optionally providing a logger factory. ```csharp var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); var downloader = new DownloadService(loggerFactory); ``` -------------------------------- ### Build Download with Package and Custom Configuration Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Builds an IDownload instance that resumes from an existing package and applies a custom DownloadConfiguration. This allows for advanced control over the download process. ```csharp public IDownload Build(DownloadPackage package, DownloadConfiguration config) ``` -------------------------------- ### Get File Name From URL Method Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Extracts the file name from the URL path, excluding any query string. ```csharp public string GetFileNameFromUrl() ``` -------------------------------- ### Task StartAsync(CancellationToken cancellationToken = default) Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-advanced.md Initiates the download process. This high-level method calls DownloadFileTaskAsync and fires all relevant events. It's the underlying method used by the IDownload interface when employing DownloadBuilder. ```APIDOC ## Task StartAsync(CancellationToken cancellationToken = default) ### Description High-level convenience method that calls `DownloadFileTaskAsync` with the current package. Fires all events. ### Method `Task` ### Parameters #### Path Parameters - **cancellationToken** (CancellationToken) - Optional - Token to cancel the operation ### Returns Task for the download operation ``` -------------------------------- ### SocketClient.GetFileInfoAsync Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-advanced.md Probes the server with a Range: 0-0 request to get file size, range support, and filename. It automatically handles redirects. ```APIDOC ## GetFileInfoAsync(Request request, CancellationToken cancel) ### Description Probes the server with a `Range: 0-0` request to get file size, range support, and filename. ### Method `async Task` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var request = new Request("https://example.com/download/file.zip?token=xyz"); var client = new SocketClient(config); var info = await client.GetFileInfoAsync(request, CancellationToken.None); ``` ### Response #### Success Response (200) - **RemoteFileInfo**: An object containing FileName (string), FileSize (long), SupportsRange (bool), and Address (string). #### Response Example ```json { "FileName": "file.zip", "FileSize": 1024000, "SupportsRange": true, "Address": "https://example.com/download/file.zip" } ``` ``` -------------------------------- ### Initialize DownloadService with Custom Configuration Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Use this constructor to set specific download parameters like chunk count and parallel download settings. Event handlers can be attached to monitor download progress. ```csharp var config = new DownloadConfiguration { ChunkCount = 8, ParallelDownload = true }; var downloader = new DownloadService(config); downloader.DownloadStarted += (s, e) => Console.WriteLine($"Started: {e.FileName}"); await downloader.DownloadFileTaskAsync("https://example.com/file.zip", @"C:\\Downloads\\file.zip"); ``` -------------------------------- ### Handle Chunk Download Retries Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Example demonstrating how to use CanTryAgainOnFailure to manage chunk download retries. If retries are exhausted, it logs the failure count. ```csharp if (chunk.CanTryAgainOnFailure()) { await RetryChunkDownload(chunk); } else { Console.WriteLine($"Chunk {chunk.Id} failed after {chunk.FailureCount} attempts"); } ``` -------------------------------- ### Simple Download with DownloadBuilder Source: https://github.com/bezzad/downloader/blob/master/README.md Use this snippet for straightforward downloads with a URL and target directory. Ensure the URL and directory paths are correctly specified. ```csharp await DownloadBuilder.New() .WithUrl(@"https://host.com/test-file.zip") .WithDirectory(@"C:\temp") .Build() .StartAsync(); ``` -------------------------------- ### Byte Range Download Configuration Source: https://github.com/bezzad/downloader/blob/master/_autodocs/configuration.md Enables byte range downloads to fetch specific portions of a file, defining the start and end bytes for the range. ```csharp var config = new DownloadConfiguration { RangeDownload = true, RangeLow = 1024, // start at byte 1024 RangeHigh = 102400 // end at byte 102400 (100KB range) }; await downloader.DownloadFileTaskAsync("https://example.com/large.iso", "partial.iso"); ``` -------------------------------- ### Get Remote File Information Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-interfaces.md Retrieves metadata for a remote file, such as its name, size, and range support, without initiating a download. This is useful for pre-download checks. ```csharp Task GetFileInfoAsync(string address, CancellationToken cancellationToken = default) ``` ```csharp var downloader = new DownloadService(config); var info = await downloader.GetFileInfoAsync("https://example.com/large.zip"); Console.WriteLine($"Will download: {info.FileName} ({info.FileSize} bytes)"); Console.WriteLine($"Range support: {info.SupportsRange}"); ``` -------------------------------- ### Resume Existing Download Package with New Configuration Source: https://github.com/bezzad/downloader/blob/master/README.md This allows resuming an existing download package while applying a new download configuration. ```csharp await DownloadBuilder.Build(package, config).StartAsync(); ``` -------------------------------- ### Download Configuration with Proxy and Custom Headers Source: https://github.com/bezzad/downloader/blob/master/_autodocs/configuration.md Sets up download configuration to use a proxy server and custom HTTP headers, including User-Agent. ```csharp var config = new DownloadConfiguration { ChunkCount = 4, ParallelDownload = true, RequestConfiguration = { Proxy = new WebProxy("http://proxy.company.com:8080"), Headers = ["Accept-Encoding: gzip, deflate"], UserAgent = "MyApp/1.0" } }; ``` -------------------------------- ### Configure Download Settings with Action Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Configures download settings via an action delegate. This is a fluent method for chaining configurations. ```csharp public DownloadBuilder Configure(Action configure) ``` -------------------------------- ### Basic Download Configuration Source: https://github.com/bezzad/downloader/blob/master/_autodocs/configuration.md Sets up a basic download configuration with chunk count, parallel download enabled, and a maximum speed limit. ```csharp var config = new DownloadConfiguration { ChunkCount = 8, ParallelDownload = true, MaximumBytesPerSecond = 1024 * 1024 * 2 // 2 MB/s }; var downloader = new DownloadService(config); ``` -------------------------------- ### Get File Name Without Downloading Source: https://github.com/bezzad/downloader/blob/master/README.md Retrieves the file name from a URL without downloading the entire file. Falls back to the URL-derived name on network errors. ```csharp string fileName = await RemoteFileResolver.GetFileNameAsync(url); ``` -------------------------------- ### Get File Name Async (Default) Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Resolves the file name from a URL using default configuration. Falls back to a URL-derived name on error instead of throwing. ```csharp public static Task GetFileNameAsync(string url, CancellationToken cancelToken = default) ``` ```csharp string fileName = await RemoteFileResolver.GetFileNameAsync("https://example.com/download/report.pdf"); Console.WriteLine($"File: {fileName}"); // May be "report.pdf" or extracted from Content-Disposition ``` -------------------------------- ### Automatic Resume Configuration Source: https://github.com/bezzad/downloader/blob/master/_autodocs/README.md Enable automatic resume functionality by setting `EnableAutoResumeDownload` to true in the configuration. Metadata is embedded in the .download file for seamless resumption. ```csharp var config = new DownloadConfiguration { EnableAutoResumeDownload = true }; ``` -------------------------------- ### Create Chunk for Specific Byte Range Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Creates a new chunk for a specific byte range within a file. Specify the inclusive start and end byte offsets. ```csharp public Chunk(long start, long end) ``` -------------------------------- ### Recommended Download Configuration Source: https://github.com/bezzad/downloader/blob/master/README.md Configure download options for speed and reliability, including chunk count, parallel downloads, retries, and auto-resume. ```csharp var downloadOpt = new DownloadConfiguration { ChunkCount = 8, // split into 8 parts... ParallelDownload = true, // ...downloaded in parallel (fast) ParallelCount = 4, // but cap concurrent connections to be a good citizen MaxTryAgainOnFailure = 5, // retry transient network errors before giving up EnableAutoResumeDownload = true,// survive crashes/network drops with zero extra code MaximumMemoryBufferBytes = 50 * 1024 * 1024, // cap RAM used for buffering (50MB) CheckDiskSizeBeforeDownload = true, // fail early if there isn't enough disk space // MaximumBytesPerSecond = 0, // 0 = unlimited; set a value to throttle }; ``` -------------------------------- ### DownloadService Constructor with LoggerFactory Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Initializes a new instance of the DownloadService with default configuration and an optional logger factory. This is a convenient option when default download settings are sufficient. ```APIDOC ## DownloadService(ILoggerFactory loggerFactory = null) ### Description Initializes a new instance with default configuration and optional logger factory. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```csharp public DownloadService(ILoggerFactory loggerFactory = null) ``` ### Parameters Details - **loggerFactory** (ILoggerFactory) - Optional - Logger factory for structured logging ### Returns New DownloadService instance with default settings ### Example ```csharp var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()); var downloader = new DownloadService(loggerFactory); ``` ``` -------------------------------- ### Configure(Action configure) Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Configures download settings via an action delegate. This method is part of the fluent configuration chain. ```APIDOC ## Configure(Action configure) ### Description Configures download settings via an action. ### Method ```csharp public DownloadBuilder Configure(Action configure) ``` ### Parameters #### Path Parameters - **configure** (Action) - Required - Action to configure the settings ### Returns The current DownloadBuilder instance for chaining ### Example ```csharp var download = DownloadBuilder.New() .WithUrl("https://example.com/file.zip") .WithDirectory(@"C:\Downloads") .Configure(opt => { opt.ChunkCount = 8; opt.ParallelDownload = true; opt.MaximumBytesPerSecond = 2 * 1024 * 1024; // 2 MB/s }) .Build(); ``` ``` -------------------------------- ### Get File Metadata Using Download Service Source: https://github.com/bezzad/downloader/blob/master/README.md Retrieves file metadata using an existing download service instance, leveraging its configuration without affecting ongoing downloads. ```csharp RemoteFileInfo info = await downloader.GetFileInfoAsync(url); ``` -------------------------------- ### Get File Name Async (Custom Configuration) Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Resolves the file name using custom configuration, including headers, proxy, and credentials. Useful for authenticated or proxied requests. ```csharp public static async Task GetFileNameAsync(string url, DownloadConfiguration configuration, CancellationToken cancelToken = default) ``` ```csharp var config = new DownloadConfiguration { RequestConfiguration = { UserAgent = "MyApp/1.0", Proxy = new WebProxy("http://proxy.example.com:8080") } }; string fileName = await RemoteFileResolver.GetFileNameAsync( "https://example.com/download/report.pdf", config ); ``` -------------------------------- ### DownloadBuilder.Build() Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Builds and returns a new IDownload instance with the configured settings. Throws an exception if the URL has not been set. ```APIDOC ## DownloadBuilder.Build() ### Description Builds and returns a new IDownload instance with configured settings. ### Method IDownload ### Returns IDownload instance ready to start. ### Throws ArgumentNullException if URL has not been declared. ### Example ```csharp var download = DownloadBuilder.New() .WithUrl("https://example.com/file.zip") .WithFileLocation(@"C:\Downloads\file.zip") .Build(); await download.StartAsync(); ``` ``` -------------------------------- ### Set Download URL with String Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Sets the download URL using a string. This is a fluent method for chaining configurations. ```csharp public DownloadBuilder WithUrl(string url) ``` -------------------------------- ### DownloadService Constructor with Configuration Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Initializes a new instance of the DownloadService with explicit download configuration and an optional logger factory. This constructor allows for fine-grained control over download behavior. ```APIDOC ## DownloadService(DownloadConfiguration options, ILoggerFactory loggerFactory = null) ### Description Initializes a new instance with explicit configuration and optional logger factory. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```csharp public DownloadService(DownloadConfiguration options, ILoggerFactory loggerFactory = null) ``` ### Parameters Details - **options** (DownloadConfiguration) - Optional - Download configuration settings - **loggerFactory** (ILoggerFactory) - Optional - Logger factory for structured logging ### Returns New DownloadService instance ready to download ### Example ```csharp var config = new DownloadConfiguration { ChunkCount = 8, ParallelDownload = true }; var downloader = new DownloadService(config); downloader.DownloadStarted += (s, e) => Console.WriteLine($"Started: {e.FileName}"); await downloader.DownloadFileTaskAsync("https://example.com/file.zip", @"C:\Downloads\file.zip"); ``` ``` -------------------------------- ### Get File Metadata Without Downloading Source: https://github.com/bezzad/downloader/blob/master/README.md Retrieves comprehensive file metadata including name, size, and range support using a lightweight header probe. Supports redirects and optional download configurations. ```csharp RemoteFileInfo info = await RemoteFileResolver.GetFileInfoAsync(url); Console.WriteLine($"{info.FileName} — {info.FileSize} bytes, range: {info.SupportsRange}"); // info.Address is the final URL after any redirects. ``` -------------------------------- ### DownloadBuilder Build Methods Source: https://github.com/bezzad/downloader/blob/master/_autodocs/INDEX.md Presents the methods for building the IDownload object from the configured DownloadBuilder, with options to build a basic download, or one based on a specific package and configuration. ```csharp // Builders IDownload Build() IDownload Build(DownloadPackage package) IDownload Build(DownloadPackage package, DownloadConfiguration config) ``` -------------------------------- ### Configure Fast and Reliable Downloads Source: https://github.com/bezzad/downloader/blob/master/_autodocs/quick-start.md Recommended configuration for robust downloads, enabling parallel chunking, retries, and auto-resume. Adjust buffer size based on memory constraints. ```csharp var config = new DownloadConfiguration { ChunkCount = 8, // 8 parallel segments ParallelDownload = true, ParallelCount = 4, // cap concurrency MaxTryAgainOnFailure = 5, // retry transient errors EnableAutoResumeDownload = true, // survive crashes MaximumMemoryBufferBytes = 50 * 1024 * 1024 // 50 MB buffer }; var downloader = new DownloadService(config); await downloader.DownloadFileTaskAsync(url, path); ``` -------------------------------- ### Pause and Resume Download Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-advanced.md Demonstrates how to pause a download when progress is between 50-60% and resume it when progress exceeds 70%. The Pause method blocks further reads, while Resume releases the pause lock. ```csharp var downloader = new DownloadService(); downloader.DownloadProgressChanged += (s, e) => { if (e.ProgressPercentage > 50 && e.ProgressPercentage < 60) { downloader.Pause(); Console.WriteLine("Paused at 50-60%"); } }; downloader.DownloadProgressChanged += (s, e) => { if (downloader.IsPaused && e.ProgressPercentage > 70) { downloader.Resume(); } }; ``` -------------------------------- ### Optimizing for Large File Downloads Source: https://github.com/bezzad/downloader/blob/master/_autodocs/README.md Prevent OutOfMemory exceptions when downloading large files by configuring buffer sizes and chunk sizes. This example sets a 256 MB buffer cap and a 1 MB minimum chunk size. ```csharp var config = new DownloadConfiguration { MaximumMemoryBufferBytes = 256 * 1024 * 1024, // 256 MB buffer cap MinimumChunkSize = 1024 * 1024 // 1 MB min per chunk }; ``` -------------------------------- ### Repository Structure Overview Source: https://github.com/bezzad/downloader/blob/master/src/CLAUDE.md Illustrates the directory layout of the Downloader project, including the main library, test projects, and sample applications. ```text src/ Downloader/ # Main library (the NuGet package) Exceptions/ # IncompleteDownloadException, FileExistException Extensions/ # ExceptionHelper, FileHelper, UrlHelper Helpers/ # internal helpers Downloader.Test/ # All tests (xUnit) UnitTests/ # Component-level tests IntegrationTests/ # End-to-end tests against DummyHttpServer HelperTests/ # Utility/server-endpoint tests Downloader.DummyHttpServer/ # ASP.NET test server used by integration tests Samples/Downloader.Sample/ # Console sample app (download.json drives URLs) .editorconfig # Authoritative code-style rules (see skill) ``` -------------------------------- ### IBinarySerializer.Deserialize(byte[] buffer, int offset, int count) Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-advanced.md Deserializes a specific portion of a byte array into an object of type T. This allows for deserialization from a buffer that may contain other data, by specifying the start offset and the number of bytes to read. ```APIDOC ## Deserialize(byte[] buffer, int offset, int count) ### Description Deserializes a range within a byte array to an object of type T. This is useful when only a part of the buffer needs to be deserialized. ### Method ``` T Deserialize(byte[] buffer, int offset, int count) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - **T**: Deserialized object of type T. #### Response Example None ``` -------------------------------- ### Check Disk Space Before Downloading Source: https://github.com/bezzad/downloader/blob/master/_autodocs/quick-start.md Enable pre-download disk space checking by setting CheckDiskSizeBeforeDownload to true in DownloadConfiguration. This prevents downloads if insufficient space is detected, throwing an exception. ```csharp var config = new DownloadConfiguration { CheckDiskSizeBeforeDownload = true // Fail if not enough space }; try { var downloader = new DownloadService(config); await downloader.DownloadFileTaskAsync(url, path); } catch (Exception ex) { Console.WriteLine($"Check failed: {ex.Message}"); } ``` -------------------------------- ### Build Docker Image Source: https://github.com/bezzad/downloader/blob/master/README.md Build a Docker image for the downloader project using the specified Dockerfile. This image can then be run as a container. ```bash docker build -f ./dockerfile -t downloader-linux . ``` -------------------------------- ### Download Configuration Options Source: https://github.com/bezzad/downloader/blob/master/src/CLAUDE.md This snippet shows the available options for configuring download behavior, including parallelism, timeouts, and file policies. Use these settings to control how downloads are performed and managed. ```csharp new DownloadConfiguration { ChunkCount = 8, // parallel segments; auto-reduced if file too small ParallelDownload = true, ParallelCount = 4, // concurrent active chunks (default = ChunkCount) MaximumBytesPerSecond = 2*MB, // 0 = unlimited BufferBlockSize = 8192, // read buffer per stream call (max 1MB) BlockTimeout = 1000, // ms timeout per ReadAsync call HttpClientTimeout = 100_000, // ms per HttpClient request MaxTryAgainOnFailure = 5, MinimumSizeOfChunking = 512, // bytes; below this = single chunk MinimumChunkSize = 0, // 0 = no constraint MaximumMemoryBufferBytes = 0, // 0 = unlimited (ConcurrentPacketBuffer cap) EnableAutoResumeDownload = false, DownloadFileExtension = ".download", FileExistPolicy = FileExistPolicy.Delete, EnableLiveStreaming = false, RangeDownload = false, // download a byte slice only CheckDiskSizeBeforeDownload = true, CustomHttpClientFactory = null, // bypass ALL internal HttpClient setup CustomHttpMessageHandlerFactory = null, // replace handler, keep header config RequestConfiguration = { AllowAutoRedirect = true, // follows 3xx including 307/308 MaximumAutomaticRedirections = 50, CookieContainer = new CookieContainer(), // default; null disables cookies // Accept, Headers, UserAgent, Proxy, Authorization, KeepAlive, ... } } ``` -------------------------------- ### DownloadService Constructors Source: https://github.com/bezzad/downloader/blob/master/_autodocs/INDEX.md Provides the signatures for creating instances of the DownloadService. One constructor accepts a DownloadConfiguration and an optional ILoggerFactory, while the other accepts only an ILoggerFactory. ```csharp // Constructors DownloadService(DownloadConfiguration options, ILoggerFactory loggerFactory = null) DownloadService(ILoggerFactory loggerFactory = null) ``` -------------------------------- ### DownloadBuilder.Build(DownloadPackage package) Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Builds and returns a new IDownload instance, resuming from an existing DownloadPackage. ```APIDOC ## DownloadBuilder.Build(DownloadPackage package) ### Description Builds and returns a new IDownload instance resuming from an existing package. ### Method IDownload ### Parameters #### Path Parameters - **package** (DownloadPackage) - Yes - Existing package with chunk state ### Returns IDownload instance ready to resume. ### Example ```csharp // Resume a previously interrupted download var download = DownloadBuilder.Build(savedPackage); await download.StartAsync(); ``` ``` -------------------------------- ### BuildStorage Method Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Creates the underlying storage for the download, which can be a file or memory stream. It allows for pre-allocation of size and setting a memory buffer cap. ```csharp public void BuildStorage(long maxMemoryBufferBytes, ILogger logger = null) ``` -------------------------------- ### Clone DownloadConfiguration Source: https://github.com/bezzad/downloader/blob/master/_autodocs/configuration.md Creates a shallow copy of the configuration object. Use this to create a modified configuration without affecting the original. ```csharp public object Clone() { return this.MemberwiseClone(); } ``` ```csharp var config1 = new DownloadConfiguration { ChunkCount = 8 }; var config2 = (DownloadConfiguration)config1.Clone(); config2.ChunkCount = 4; // config1 unchanged ``` -------------------------------- ### Download Configuration with Authentication Source: https://github.com/bezzad/downloader/blob/master/_autodocs/configuration.md Configures authentication for downloads, supporting either a Bearer token or basic network credentials. ```csharp var config = new DownloadConfiguration { ChunkCount = 4, ParallelDownload = true, RequestConfiguration = { Authorization = new AuthenticationHeaderValue("Bearer", "your_token_here"), // OR use credentials: Credentials = new NetworkCredential("user", "password") } }; ``` -------------------------------- ### Configure Logging for Downloads Source: https://github.com/bezzad/downloader/blob/master/_autodocs/quick-start.md Integrate Microsoft.Extensions.Logging by providing a LoggerFactory instance to the DownloadService constructor. This allows for detailed debugging and monitoring of download operations. ```csharp using Microsoft.Extensions.Logging; var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Debug) ); var downloader = new DownloadService( new DownloadConfiguration { ChunkCount = 4 }, loggerFactory ); await downloader.DownloadFileTaskAsync(url, path); ``` -------------------------------- ### DownloadBuilder.Build(DownloadPackage package, DownloadConfiguration config) Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Builds and returns a new IDownload instance using an existing DownloadPackage and custom DownloadConfiguration. ```APIDOC ## DownloadBuilder.Build(DownloadPackage package, DownloadConfiguration config) ### Description Builds and returns a new IDownload instance with package and custom configuration. ### Method IDownload ### Parameters #### Path Parameters - **package** (DownloadPackage) - Yes - Existing package with chunk state - **config** (DownloadConfiguration) - Yes - Download configuration settings ### Returns IDownload instance ready to resume with new settings. ``` -------------------------------- ### WithDirectory(string directoryPath) Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-main-services.md Sets the directory where the downloaded file will be saved. This method is part of the fluent configuration chain. ```APIDOC ## WithDirectory(string directoryPath) ### Description Sets the directory where the file will be saved. ### Method ```csharp public DownloadBuilder WithDirectory(string directoryPath) ``` ### Parameters #### Path Parameters - **directoryPath** (string) - Required - Directory path for the downloaded file ### Returns The current DownloadBuilder instance for chaining ``` -------------------------------- ### Quick Pause and Resume Download Source: https://github.com/bezzad/downloader/blob/master/README.md This snippet shows how to quickly pause and resume a download within the `DownloadProgressChanged` event handler. Ensure the `url` and `path` variables are defined before use. ```csharp var download = DownloadBuilder.New() .WithUrl(url) .WithFileLocation(path) .Build(); download.DownloadProgressChanged += (_, _) => { download.Pause(); // pause current download quickly download.Resume(); // continue current download quickly }; await download.StartAsync(); ``` -------------------------------- ### Resume() Source: https://github.com/bezzad/downloader/blob/master/_autodocs/api-reference-interfaces.md Resumes a download that was previously paused. ```APIDOC ## Resume() ### Description Resumes a paused download from where it was suspended. ### Method void ### Request Example ```csharp downloader.Pause(); await Task.Delay(TimeSpan.FromSeconds(5)); downloader.Resume(); ``` ``` -------------------------------- ### Perform a Simple File Download Source: https://github.com/bezzad/downloader/blob/master/_autodocs/quick-start.md Use the DownloadService to download a file to a specified path. Ensure the Downloader namespace is included. ```csharp using Downloader; var downloader = new DownloadService(); await downloader.DownloadFileTaskAsync( "https://example.com/file.zip", @"C:\\Downloads\\file.zip" ); ``` -------------------------------- ### TrySetCompleteState Method Source: https://github.com/bezzad/downloader/blob/master/_autodocs/types.md Atomically attempts to transition the download to a terminal state (Completed, Failed, or Stopped). Returns false if the package is already in a terminal state. Optionally clears the package on failure. ```csharp public async Task TrySetCompleteState(DownloadStatus state, bool clearPackageOnCompletionWithFailure = false) ``` -------------------------------- ### Pack NuGet Package in Release Mode Source: https://github.com/bezzad/downloader/blob/master/CLAUDE.md Use this command to pack the NuGet package in Release mode. The output is directed to the standard package output location. ```bash dotnet pack src/Downloader/Downloader.csproj -c Release -o src/Downloader/bin/nupkg/ ```