### Install HttpMultipartParser NuGet Package Source: https://github.com/http-multipart-data-parser/httpmultipartparser/blob/develop/README.md Use the Package Manager Console to install the HttpMultipartParser NuGet package into your project. ```csharp PM> Install-Package HttpMultipartParser ``` -------------------------------- ### Install HttpMultipartParser via NuGet Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Use the NuGet Package Manager or the .NET CLI to add the HttpMultipartParser library to your project. ```bash # Package Manager Install-Package HttpMultipartParser # .NET CLI dotnet add package HttpMultipartParser ``` -------------------------------- ### Parse Multiple Parameters Source: https://github.com/http-multipart-data-parser/httpmultipartparser/blob/develop/README.md Example of the multipart stream format for multiple parameters and the corresponding C# parsing logic. ```text // stream: -----------------------------41952539122868 Content-Disposition: form-data; name="checkbox" likes_cake -----------------------------41952539122868 Content-Disposition: form-data; name="checkbox" likes_cookies -----------------------------41952539122868-- ``` ```csharp // ===== Simple Parsing ==== // You can parse synchronously: var parser = MultipartFormDataParser.Parse(stream); // Or you can parse asynchronously: var parser = await MultipartFormDataParser.ParseAsync(stream).ConfigureAwait(false); // From this point the data is parsed, we can retrieve the // form data from the GetParameterValues method var checkboxResponses = parser.GetParameterValues("checkbox"); foreach(var parameter in checkboxResponses) { Console.WriteLine("Parameter {0} is {1}", parameter.Name, parameter.Data) } ``` -------------------------------- ### Parse Multiple Files Source: https://github.com/http-multipart-data-parser/httpmultipartparser/blob/develop/README.md Example of the multipart stream format for multiple files and the corresponding C# parsing logic, including advanced streaming. ```text // stream: -----------------------------41111539122868 Content-Disposition: form-data; name="files[]"; filename="photo1.jpg" Content-Type: image/jpeg MoreBinaryData -----------------------------41111539122868 Content-Disposition: form-data; name="files[]"; filename="photo2.jpg" Content-Type: image/jpeg ImagineLotsOfBinaryData -----------------------------41111539122868-- ``` ```csharp // ===== Simple Parsing ==== // You can parse synchronously: var parser = MultipartFormDataParser.Parse(stream); // Or you can parse asynchronously: var parser = await MultipartFormDataParser.ParseAsync(stream).ConfigureAwait(false); // Loop through all the files foreach(var file in parser.Files) { Stream data = file.Data; // Do stuff with the data. } // ==== Advanced Parsing ==== var parser = new StreamingMultipartFormDataParser(stream); parser.ParameterHandler += parameter => DoSomethingWithParameter(parameter); parser.FileHandler += (name, fileName, type, disposition, buffer, bytes, partNumber, additionalProperties) => { // Write the part of the file we've received to a file stream. (Or do something else) // Assume that filesreamsByName is a Dictionary of all the files // we are writing. filestreamsByName[name].Write(buffer, 0, bytes); }; parser.StreamClosedHandler += () { // Do things when my input stream is closed }; // You can parse synchronously: parser.Run(); // Or you can parse asynchronously: await parser.RunAsync().ConfigureAwait(false); ``` -------------------------------- ### Get Multiple Parameter Values Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Retrieves all values for a parameter that may appear multiple times, common for checkbox groups or multi-select fields. Supports case-insensitive comparison. ```csharp using HttpMultipartParser; using System; using System.Linq; // Multipart data with multiple values for same parameter: // -----------------------------boundary // Content-Disposition: form-data; name="colors" // // red // -----------------------------boundary // Content-Disposition: form-data; name="colors" // // green // -----------------------------boundary // Content-Disposition: form-data; name="colors" // // blue // -----------------------------boundary-- var parser = MultipartFormDataParser.Parse(stream); // Get all values for a multi-value parameter var selectedColors = parser.GetParameterValues("colors").ToList(); // Result: ["red", "green", "blue"] foreach (var color in selectedColors) { Console.WriteLine($"Selected color: {color}"); } // With case-insensitive comparison var tags = parser.GetParameterValues("Tags", StringComparison.OrdinalIgnoreCase); ``` -------------------------------- ### Get Single Parameter Value Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Retrieves a single parameter value from parsed multipart data. Returns the first value if multiple parameters share the same name. Use case-insensitive comparison by providing a StringComparison option. ```csharp using HttpMultipartParser; using System; var parser = MultipartFormDataParser.Parse(stream); // Get single parameter value (returns first if multiple exist) string username = parser.GetParameterValue("username"); // Get parameter with case-insensitive comparison string email = parser.GetParameterValue("Email", StringComparison.OrdinalIgnoreCase); // Check for null if parameter might not exist string optionalField = parser.GetParameterValue("optional_field"); if (optionalField != null) { Console.WriteLine($"Optional field value: {optionalField}"); } ``` -------------------------------- ### Parse Multipart Data with ParserOptions Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Configures parsing behavior such as boundary detection, buffer size, and error handling using the ParserOptions class. ```csharp using HttpMultipartParser; using System.IO; using System.Text; // Create parser options with custom configuration var options = new ParserOptions { // Explicitly set boundary (optional - auto-detected if null) Boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW", // Set character encoding (default: UTF-8) Encoding = Encoding.UTF8, // Buffer size for parsing (default: 4096) // Must be larger than: boundary length + 4 + newline bytes BinaryBufferSize = 8192, // MIME types to treat as binary files (default: application/octet-stream) BinaryMimeTypes = new[] { "application/octet-stream", "application/pdf", "image/png" }, // Ignore malformed parts instead of throwing exceptions IgnoreInvalidParts = true }; // Parse with custom options Stream stream = GetMultipartStream(); var parser = MultipartFormDataParser.Parse(stream, options); // Process parsed data foreach (var param in parser.Parameters) { Console.WriteLine($"Parameter: {param.Name} = {param.Data}"); } foreach (var file in parser.Files) { Console.WriteLine($"File: {file.FileName} ({file.ContentType})"); Console.WriteLine($"Additional Properties: {string.Join(", ", file.AdditionalProperties)}"); } ``` -------------------------------- ### Stream Multipart Data with Event Handlers Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Processes multipart data chunks via events to handle large files without loading the entire stream into memory. ```csharp using HttpMultipartParser; using System.Collections.Generic; using System.IO; Stream multipartStream = GetLargeMultipartStream(); // Create the streaming parser var parser = new StreamingMultipartFormDataParser(multipartStream); // Dictionary to store parameters var parameters = new Dictionary(); // Dictionary to track file streams by field name var fileStreams = new Dictionary(); // Handle form parameters as they arrive parser.ParameterHandler += parameter => { parameters[parameter.Name] = parameter.Data; Console.WriteLine($"Received parameter: {parameter.Name} = {parameter.Data}"); }; // Handle file data chunks as they stream in parser.FileHandler += (name, fileName, contentType, contentDisposition, buffer, bytes, partNumber, additionalProperties) => { // Create file stream on first chunk (partNumber == 0) if (partNumber == 0) { var savePath = Path.Combine("/uploads", fileName); fileStreams[name] = new FileStream(savePath, FileMode.Create, FileAccess.Write); Console.WriteLine($"Started receiving file: {fileName} ({contentType})"); } // Write chunk to file fileStreams[name].Write(buffer, 0, bytes); Console.WriteLine($"Received chunk {partNumber} for {fileName}: {bytes} bytes"); }; // Handle stream completion parser.StreamClosedHandler += () => { // Close all file streams foreach (var fs in fileStreams.Values) { fs.Close(); } Console.WriteLine("Stream parsing completed"); }; // Execute the parser synchronously parser.Run(); // Access collected parameters Console.WriteLine($"Username: {parameters["username"]}"); ``` -------------------------------- ### Run Streaming Parser Asynchronously Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Executes the streaming parser using RunAsync, supporting cancellation tokens for concurrent server environments. ```csharp using HttpMultipartParser; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; public async Task ProcessLargeUploadAsync(Stream requestStream, CancellationToken cancellationToken) { var parser = new StreamingMultipartFormDataParser(requestStream); var formData = new Dictionary(); var uploadedFiles = new List(); FileStream currentFileStream = null; parser.ParameterHandler += param => { formData[param.Name] = param.Data; }; parser.FileHandler += (name, fileName, contentType, disposition, buffer, bytes, partNumber, props) => { if (partNumber == 0) { // Close previous file if any currentFileStream?.Close(); var path = Path.Combine("/uploads", Guid.NewGuid() + "_" + fileName); currentFileStream = new FileStream(path, FileMode.Create); uploadedFiles.Add(path); } currentFileStream.Write(buffer, 0, bytes); }; parser.StreamClosedHandler += () => { currentFileStream?.Close(); }; // Run asynchronously with cancellation support await parser.RunAsync(cancellationToken).ConfigureAwait(false); Console.WriteLine($"Processed {uploadedFiles.Count} files"); Console.WriteLine($"Form data: {string.Join(", ", formData.Keys)}"); } ``` -------------------------------- ### Simple Synchronous Parsing Source: https://github.com/http-multipart-data-parser/httpmultipartparser/blob/develop/README.md Parse a multipart/form-data stream synchronously. This method is suitable for smaller files as it reads the entire stream. ```csharp // stream: -----------------------------41952539122868 Content-Disposition: form-data; name="username" example -----------------------------41952539122868 Content-Disposition: form-data; name="email" example@data.com -----------------------------41952539122868 Content-Disposition: form-data; name="files[]"; filename="photo1.jpg" Content-Type: image/jpeg ExampleBinaryData012031203 -----------------------------41952539122868-- ``` ```csharp // ===== Simple Parsing ==== // You can parse synchronously: var parser = MultipartFormDataParser.Parse(stream); // Or you can parse asynchronously: var parser = await MultipartFormDataParser.ParseAsync(stream).ConfigureAwait(false); // From this point the data is parsed, we can retrieve the // form data using the GetParameterValue method. var username = parser.GetParameterValue("username"); var email = parser.GetParameterValue("email"); // Files are stored in a list: var file = parser.Files.First(); string filename = file.FileName; Stream data = file.Data; ``` -------------------------------- ### ParameterPart Properties for Parsed Parameters Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Iterates through ParameterPart objects to access the name and data of each form parameter. Demonstrates grouping parameters by name for multi-value fields. ```csharp using HttpMultipartParser; var parser = MultipartFormDataParser.Parse(stream); // Access all parameters directly foreach (var parameter in parser.Parameters) { // Name: The form field name Console.WriteLine($"Name: {parameter.Name}"); // Data: The string value of the parameter Console.WriteLine($"Value: {parameter.Data}"); } // Group parameters by name for multi-value fields var groupedParams = parser.Parameters .GroupBy(p => p.Name) .ToDictionary(g => g.Key, g => g.Select(p => p.Data).ToList()); foreach (var group in groupedParams) { if (group.Value.Count == 1) { Console.WriteLine($"{group.Key}: {group.Value[0]}"); } else { Console.WriteLine($"{group.Key}: [{string.Join(", ", group.Value)}]"); } } ``` -------------------------------- ### Synchronously Parse Multipart Form Data Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Use the static MultipartFormDataParser.Parse method for synchronous parsing of multipart/form-data streams. This is suitable for smaller uploads where loading all data into memory is acceptable. It automatically detects the boundary and provides access to parameters and files. ```csharp using HttpMultipartParser; using System.IO; using System.Text; // Example multipart/form-data stream content: // -----------------------------41952539122868 // Content-Disposition: form-data; name="username" // // john_doe // -----------------------------41952539122868 // Content-Disposition: form-data; name="email" // // john@example.com // -----------------------------41952539122868 // Content-Disposition: form-data; name="avatar"; filename="photo.jpg" // Content-Type: image/jpeg // // // -----------------------------41952539122868-- // Parse with automatic boundary detection Stream multipartStream = GetMultipartStreamFromRequest(); var parser = MultipartFormDataParser.Parse(multipartStream); // Access form parameters string username = parser.GetParameterValue("username"); // "john_doe" string email = parser.GetParameterValue("email"); // "john@example.com" // Check if parameter exists bool hasUsername = parser.HasParameter("username"); // true // Access uploaded files foreach (var file in parser.Files) { Console.WriteLine($"Field Name: {file.Name}"); // "avatar" Console.WriteLine($"File Name: {file.FileName}"); // "photo.jpg" Console.WriteLine($"Content Type: {file.ContentType}"); // "image/jpeg" // Save file to disk using (var fileStream = File.Create($"/uploads/{file.FileName}")) { file.Data.CopyTo(fileStream); } } ``` -------------------------------- ### Streaming Parsing for Large Files Source: https://github.com/http-multipart-data-parser/httpmultipartparser/blob/develop/README.md Parse multipart/form-data streams using a streaming approach, which is ideal for handling large files without loading the entire content into memory. Set up ParameterHandler and FileHandler delegates to process data as it arrives. ```csharp // ==== Advanced Parsing ==== var parser = new StreamingMultipartFormDataParser(stream); parser.ParameterHandler += parameter => DoSomethingWithParameter(parameter); parser.FileHandler += (name, fileName, type, disposition, buffer, bytes, partNumber, additionalProperties) => { // Write the part of the file we've received to a file stream. (Or do something else) filestream.Write(buffer, 0, bytes); }; // You can parse synchronously: parser.Run(); // Or you can parse asynchronously: await parser.RunAsync().ConfigureAwait(false); ``` -------------------------------- ### Asynchronously Parse Multipart Form Data Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Use the static MultipartFormDataParser.ParseAsync method for asynchronous parsing of multipart/form-data streams, supporting cancellation. This is recommended for I/O-bound operations in async contexts to avoid blocking threads. It processes data through callbacks as it arrives, ideal for large files. ```csharp using HttpMultipartParser; using System.IO; using System.Threading; using System.Threading.Tasks; public async Task UploadFileAsync(Stream requestStream, CancellationToken cancellationToken) { // Parse asynchronously with cancellation support var parser = await MultipartFormDataParser.ParseAsync( requestStream, cancellationToken: cancellationToken ).ConfigureAwait(false); // Access parameters string title = parser.GetParameterValue("title"); string description = parser.GetParameterValue("description"); // Process all uploaded files var uploadedFiles = new List(); foreach (var file in parser.Files) { var savePath = Path.Combine("/uploads", file.FileName); using (var output = File.Create(savePath)) { await file.Data.CopyToAsync(output, cancellationToken); } uploadedFiles.Add(savePath); } return Ok(new { Title = title, Files = uploadedFiles }); } ``` -------------------------------- ### FilePart Properties Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Access properties of parsed files including name, filename, data stream, and content type. ```APIDOC ## FilePart ### Description Represents a parsed file within the multipart data. ### Properties - **Name** (string) - The form field name. - **FileName** (string) - The original filename. - **Data** (Stream) - The file content stream. - **ContentType** (string) - The MIME type of the file. - **ContentDisposition** (string) - The content disposition header value. - **AdditionalProperties** (Dictionary) - Extra properties from the Content-Disposition header. ``` -------------------------------- ### GetParameterValues Extension Method Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Retrieves multiple values for parameters with the same name, useful for multi-select fields. ```APIDOC ## GetParameterValues ### Description Retrieves all values associated with a specific parameter name. ### Parameters - **name** (string) - Required - The name of the parameter. - **comparison** (StringComparison) - Optional - Comparison type for case-insensitive matching. ### Response - **values** (IEnumerable) - A collection of all values found for the given parameter name. ``` -------------------------------- ### ParameterPart Properties Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Access properties of parsed form parameters. ```APIDOC ## ParameterPart ### Description Represents a parsed form parameter. ### Properties - **Name** (string) - The form field name. - **Data** (string) - The string value of the parameter. ``` -------------------------------- ### Check for Parameter Existence Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Checks if a parameter exists within the parsed form data before attempting to access its value. This prevents null reference exceptions. ```csharp using HttpMultipartParser; var parser = MultipartFormDataParser.Parse(stream); // Check if parameter exists before accessing if (parser.HasParameter("remember_me")) { bool rememberMe = parser.GetParameterValue("remember_me") == "true"; Console.WriteLine($"Remember me: {rememberMe}"); } // Conditional logic based on presence if (parser.HasParameter("premium_features")) { EnablePremiumFeatures(parser.GetParameterValues("premium_features")); } ``` -------------------------------- ### MultipartFormDataParser.Parse Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Synchronously parses a multipart/form-data stream into a parser object. This method is recommended for smaller uploads where loading the data into memory is acceptable. ```APIDOC ## MultipartFormDataParser.Parse ### Description Synchronously parses a multipart/form-data stream into a parser object containing all parameters and files. ### Method Static Method ### Parameters #### Request Body - **multipartStream** (Stream) - Required - The input stream containing the multipart/form-data content. ### Response - **parser** (MultipartFormDataParser) - An object containing parsed parameters and file collections. ``` -------------------------------- ### MultipartFormDataParser.ParseAsync Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Asynchronously parses a multipart/form-data stream into a parser object. This method is ideal for async contexts to prevent blocking threads during I/O operations. ```APIDOC ## MultipartFormDataParser.ParseAsync ### Description Asynchronously parses a multipart/form-data stream into a parser object containing all parameters and files. ### Method Static Method (Async) ### Parameters #### Request Body - **requestStream** (Stream) - Required - The input stream containing the multipart/form-data content. - **cancellationToken** (CancellationToken) - Optional - Token to cancel the asynchronous operation. ### Response - **parser** (Task) - A task representing the asynchronous operation, resulting in a parser object. ``` -------------------------------- ### FilePart Properties for Parsed Files Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Accesses properties of a FilePart object, including its name, original filename, data stream, content type, content disposition, and any additional properties. ```csharp using HttpMultipartParser; using System.IO; var parser = MultipartFormDataParser.Parse(stream); foreach (var file in parser.Files) { // Name: The form field name (e.g., "document", "avatar") Console.WriteLine($"Field Name: {file.Name}"); // FileName: The original filename (sanitized, path components removed) Console.WriteLine($"File Name: {file.FileName}"); // Data: Stream containing the file bytes Console.WriteLine($"File Size: {file.Data.Length} bytes"); // ContentType: MIME type (defaults to "text/plain" if unspecified) Console.WriteLine($"Content Type: {file.ContentType}"); // ContentDisposition: Usually "form-data" Console.WriteLine($"Content Disposition: {file.ContentDisposition}"); // AdditionalProperties: Any extra properties from Content-Disposition header foreach (var prop in file.AdditionalProperties) { Console.WriteLine($"Additional Property: {prop.Key} = {prop.Value}"); } // Save file based on content type string extension = file.ContentType switch { "image/jpeg" => ".jpg", "image/png" => ".png", "application/pdf" => ".pdf", _ => Path.GetExtension(file.FileName) }; using var outputStream = File.Create($"/uploads/{Guid.NewGuid()}{extension}"); file.Data.CopyTo(outputStream); } ``` -------------------------------- ### HasParameter Extension Method Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Checks if a specific parameter exists in the parsed form data. ```APIDOC ## HasParameter ### Description Checks if a parameter exists in the parsed form data. ### Parameters - **name** (string) - Required - The name of the parameter to check. ### Response - **exists** (bool) - Returns true if the parameter exists, otherwise false. ``` -------------------------------- ### GetParameterValue Extension Method Source: https://context7.com/http-multipart-data-parser/httpmultipartparser/llms.txt Retrieves a single parameter value from the parsed result. Returns null if the parameter does not exist. ```APIDOC ## GetParameterValue ### Description Retrieves a single parameter value from the parsed result. Returns null if the parameter doesn't exist. ### Parameters - **name** (string) - Required - The name of the parameter to retrieve. - **comparison** (StringComparison) - Optional - Comparison type for case-insensitive matching. ### Request Example parser.GetParameterValue("username"); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.