### Install Mime-Detective via NuGet Source: https://github.com/mediatedcommunications/mime-detective/blob/main/README.md Commands to install the Mime-Detective library and its various definition packs using the NuGet package manager. ```bash install-package Mime-Detective install-package Mime-Detective.Definitions.Condensed install-package Mime-Detective.Definitions.Exhaustive ``` -------------------------------- ### ContentReader for Controlling File Reading Behavior Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt Demonstrates how to use the `ContentReader` class to control the amount of data read from files or streams for Mime-Detective inspections. It shows examples of using default, minimum, maximum, and custom readers to balance detection accuracy and performance. ```csharp using MimeDetective; using MimeDetective.Definitions; var inspector = new ContentInspectorBuilder { Definitions = DefaultDefinitions.All() }.Build(); // Use default reader (up to 10MB) var defaultResults = inspector.Inspect("/path/to/large-file.bin"); // Use minimum reader for quick detection (only first 1KB) // Faster but may miss signatures that appear later in the file var quickResults = inspector.Inspect( File.OpenRead("/path/to/file.bin"), reader: ContentReader.Min ); // Use maximum reader for thorough detection (up to 2GB) // Slower but catches signatures anywhere in the file var thoroughResults = inspector.Inspect( File.OpenRead("/path/to/file.bin"), reader: ContentReader.Max ); // Create custom reader for specific file size limit var customReader = new ContentReader { MaxFileSize = 50 * 1024 }; // 50KB limit var customResults = inspector.Inspect( File.OpenRead("/path/to/file.bin"), reader: customReader ); // Read from stream factory (useful for lazy loading) byte[] content = customReader.ReadFromStream(() => File.OpenRead("/path/to/file.bin")); ``` -------------------------------- ### Convert MIME Types to File Extensions using MimeTypeToFileExtensionLookup Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt Details the usage of the `MimeTypeToFileExtensionLookup` class for efficiently converting MIME types back to their associated file extensions. This is beneficial when a MIME type is known and the corresponding file extension is required. The example shows how to retrieve the most common extension and all possible extensions for a given MIME type, including handling unknown MIME types. ```csharp using MimeDetective; using MimeDetective.Definitions; // Load definitions once and reuse var definitions = DefaultDefinitions.All(); // Build the lookup var mimeToExtension = new MimeTypeToFileExtensionLookupBuilder { Definitions = definitions }.Build(); // Get single extension (most common) var extension = mimeToExtension.TryGetValue("image/jpeg"); Console.WriteLine($"image/jpeg -> .{extension}"); // Output: image/jpeg -> .jpg // Get all possible extensions for a MIME type var allExtensions = mimeToExtension.TryGetValues("image/tiff"); foreach (var match in allExtensions) { Console.WriteLine($"image/tiff -> .{match.Extension} (Points: {match.Points})"); } // Output: image/tiff -> .TIF (Points: 4) // image/tiff -> .TIFF (Points: 4) // Handle unknown MIME types var unknownExt = mimeToExtension.TryGetValue("application/x-unknown"); if (unknownExt == null) { Console.WriteLine("Unknown MIME type"); } ``` -------------------------------- ### Initialize Predefined Definition Sets Source: https://github.com/mediatedcommunications/mime-detective/blob/main/README.md Demonstrates how to initialize the Condensed and Exhaustive definition builders. Requires specifying the correct Licensing.UsageType based on your project's commercial or personal status. ```csharp var AllDefintions = new Definitions.CondensedBuilder() { UsageType = Definitions.Licensing.UsageType.PersonalNonCommercial }.Build(); var AllDefintions = new Definitions.ExhaustiveBuilder() { UsageType = Definitions.Licensing.UsageType.PersonalNonCommercial }.Build(); ``` -------------------------------- ### Build Definitions and Lookups Once in C# Source: https://github.com/mediatedcommunications/mime-detective/blob/main/README.md Demonstrates how to efficiently build definitions and lookup tables (MIME type to file extensions, and file extensions to MIME types) once and reuse them. This avoids repeated initialization costs and improves overall application performance. ```csharp var AllDefintions = new Definitions.ExhaustiveBuilder() { UsageType = Definitions.Licensing.UsageType.PersonalNonCommercial }.Build(); var Inspector = new ContentInspectorBuilder() { Definitions = AllDefintions, }.Build(); var MimeTypeToFileExtensions = new MimeTypeToFileExtensionLookupBuilder() { Definitions = AllDefintions, }.Build(); var FileExtensionToMimeTypes = new FileExtensionToMimeTypeLookupBuilder() { Definitions = AllDefintions, }.Build(); ``` -------------------------------- ### Initialize ContentInspector Source: https://github.com/mediatedcommunications/mime-detective/blob/main/README.md Demonstrates how to instantiate a ContentInspector using different definition packs (Default, Condensed, or Exhaustive) to configure detection capabilities. ```csharp using MimeDetective; // Default var Inspector = new ContentInspectorBuilder() { Definitions = MimeDetective.Definitions.DefaultDefinitions.All() }.Build(); // Condensed var Inspector = new ContentInspectorBuilder() { Definitions = new Definitions.CondensedBuilder() { UsageType = Definitions.Licensing.UsageType.PersonalNonCommercial }.Build() }.Build(); // Exhaustive var Inspector = new ContentInspectorBuilder() { Definitions = new Definitions.ExhaustiveBuilder() { UsageType = Definitions.Licensing.UsageType.PersonalNonCommercial }.Build() }.Build(); ``` -------------------------------- ### Create Custom Definition Packs Source: https://github.com/mediatedcommunications/mime-detective/blob/main/README.md Shows how to build a custom ContentInspector by combining predefined audio definitions with a custom file signature definition using StringSegment and PrefixSegment rules. ```csharp internal static class CustomContentInspector { public static ContentInspector Instance { get; } static CustomContentInspector() { var MyDefinitions = new List(); MyDefinitions.AddRange(MimeDetective.Definitions.DefaultDefinitions.FileTypes.Audio.MP3()); MyDefinitions.Add(new() { File = new() { Categories = new[] { Category.Other }.ToImmutableHashSet(), Description = "Magic File Type", Extensions = new[] { "magic" }.ToImmutableArray(), MimeType = "application/octet-stream", }, Signature = new Segment[] { StringSegment.Create("MAGIC"), PrefixSegment.Create(100, "4d 41 47 49 43") }.ToSignature(), }); Instance = new ContentInspectorBuilder() { Definitions = MyDefinitions, StringSegmentOptions = new() { OptimizeFor = Engine.StringSegmentResourceOptimization.HighSpeed, }, }.Build(); } } ``` -------------------------------- ### Build ContentInspector with Different Definitions - C# Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt Demonstrates how to create an IContentInspector instance using ContentInspectorBuilder with various definition packs (Default, Condensed, Exhaustive). It also shows how to configure optimizations for high-speed or low-memory usage. ```csharp using MimeDetective; using MimeDetective.Definitions; using MimeDetective.Engine; // Create inspector with Default definitions (small, free for any use) var defaultInspector = new ContentInspectorBuilder { Definitions = DefaultDefinitions.All() }.Build(); // Create inspector with Condensed definitions (medium size, requires license for commercial use) var condensedInspector = new ContentInspectorBuilder { Definitions = new Definitions.CondensedBuilder { UsageType = Definitions.Licensing.UsageType.PersonalNonCommercial }.Build() }.Build(); // Create inspector with Exhaustive definitions (14,000+ signatures, requires license for commercial use) var exhaustiveInspector = new ContentInspectorBuilder { Definitions = new Definitions.ExhaustiveBuilder { UsageType = Definitions.Licensing.UsageType.CommercialPaid }.Build() }.Build(); // Create inspector optimized for high-speed detection with parallel processing var highSpeedInspector = new ContentInspectorBuilder { Definitions = DefaultDefinitions.All(), Parallel = true, StringSegmentOptions = new() { OptimizeFor = StringSegmentResourceOptimization.HighSpeed } }.Build(); // Create inspector optimized for low memory usage var lowMemoryInspector = new ContentInspectorBuilder { Definitions = DefaultDefinitions.All(), Parallel = false, StringSegmentOptions = new() { OptimizeFor = StringSegmentResourceOptimization.LowMemory } }.Build(); ``` -------------------------------- ### Convert File Extensions to MIME Types using FileExtensionToMimeTypeLookup Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt Explains how to use the `FileExtensionToMimeTypeLookup` class for fast conversion of file extensions to their corresponding MIME types. This is useful when the file extension is trusted and direct MIME type retrieval is needed without content analysis. It covers single and multiple MIME type lookups, including handling unknown extensions. ```csharp using MimeDetective; using MimeDetective.Definitions; // Load definitions once and reuse var definitions = new Definitions.ExhaustiveBuilder { UsageType = Definitions.Licensing.UsageType.PersonalNonCommercial }.Build(); // Build the lookup var extensionToMime = new FileExtensionToMimeTypeLookupBuilder { Definitions = definitions }.Build(); // Get single MIME type (most common) var mimeType = extensionToMime.TryGetValue("jpg"); Console.WriteLine($".jpg -> {mimeType}"); // Output: .jpg -> IMAGE/JPEG // Also works with leading dot var mimeType2 = extensionToMime.TryGetValue(".png"); Console.WriteLine($".png -> {mimeType2}"); // Output: .png -> IMAGE/PNG // Get all possible MIME types for an extension (some extensions map to multiple types) var allMimeTypes = extensionToMime.TryGetValues("xml"); foreach (var match in allMimeTypes) { Console.WriteLine($".xml -> {match.MimeType} (Points: {match.Points})"); } // Handle unknown extensions var unknownMime = extensionToMime.TryGetValue("xyz"); if (unknownMime == null) { Console.WriteLine("Unknown file extension"); } ``` -------------------------------- ### Building Custom Content Inspectors Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt This snippet demonstrates how to combine specific or categorized definitions to build a custom `IContentInspector` for focused file type detection. ```APIDOC ## Building Custom Content Inspectors ### Description This section illustrates how to create a specialized `IContentInspector` by combining selected definitions from the DefaultDefinitions pack. This allows for more targeted file type detection based on specific needs. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A ### Request Example ```csharp using MimeDetective; using MimeDetective.Definitions; // Combine specific definitions for a focused inspector var imageAudioInspector = new ContentInspectorBuilder { Definitions = [ .. DefaultDefinitions.FileTypes.Images.All(), .. DefaultDefinitions.FileTypes.Audio.All() ] }.Build(); ``` ### Response N/A (Code Example) ### Response Example N/A (Code Example) ``` -------------------------------- ### POST /definitions/optimize Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt Optimize memory usage by scoping definitions to specific extensions and trimming unnecessary metadata. ```APIDOC ## POST /definitions/optimize ### Description Reduces the memory footprint of the inspector by filtering definitions to specific extensions and removing unused metadata fields like descriptions or categories. ### Method POST ### Endpoint /definitions/optimize ### Parameters #### Query Parameters - **scope** (Array) - Optional - List of extensions to keep. - **trimMeta** (Boolean) - Optional - If true, removes author and date metadata. - **trimDescription** (Boolean) - Optional - If true, removes description fields. ### Request Example { "scope": ["mp3", "wav"], "trimMeta": true, "trimDescription": true } ### Response #### Success Response (200) - **OptimizedCount** (Integer) - Number of definitions remaining after optimization. ``` -------------------------------- ### Detect File Type using IContentInspector.Inspect - C# Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt Shows how to use the Inspect method of an IContentInspector to detect file types from different input sources like byte arrays, file paths, streams, and byte spans. It also explains how to process the detection results. ```csharp using MimeDetective; using MimeDetective.Definitions; using MimeDetective.Engine; var inspector = new ContentInspectorBuilder { Definitions = DefaultDefinitions.All() }.Build(); // Inspect from byte array byte[] pngHeader = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; var resultFromBytes = inspector.Inspect(pngHeader); // Inspect from file path var resultFromFile = inspector.Inspect("/path/to/image.png"); // Inspect from stream using var stream = File.OpenRead("/path/to/document.pdf"); var resultFromStream = inspector.Inspect(stream); // Inspect from stream with position reset (useful when stream needs reuse) using var reusableStream = File.OpenRead("/path/to/file.jpg"); var resultWithReset = inspector.Inspect(reusableStream, resetPosition: true); // Stream position is now back to original position // Inspect partial byte array byte[] largeBuffer = new byte[1024]; // ... fill buffer ... var resultFromSlice = inspector.Inspect(largeBuffer, start: 0, length: 512); // Process detection results foreach (var match in resultFromFile.OrderByDescending(m => m.Points)) { if (match.Type == DefinitionMatchType.Complete) { Console.WriteLine($"Extension: {match.Definition.File.Extensions.First()}"); Console.WriteLine($"MIME Type: {match.Definition.File.MimeType}"); Console.WriteLine($"Description: {match.Definition.File.Description}"); Console.WriteLine($"Confidence Points: {match.Points}"); Console.WriteLine($"Match Percentage: {match.Percentage:P}"); } } ``` -------------------------------- ### POST /definitions/custom Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt Create and register custom file type detection rules using signature segments. ```APIDOC ## POST /definitions/custom ### Description Defines new file types by specifying byte patterns (PrefixSegment) or arbitrary string patterns (StringSegment) to identify custom file formats. ### Method POST ### Endpoint /definitions/custom ### Parameters #### Request Body - **File** (Object) - Required - Contains Extensions, MimeType, Description, and Categories. - **Signature** (Array) - Required - A collection of PrefixSegment or StringSegment objects defining the file signature. ### Request Example { "File": { "Extensions": ["myformat"], "MimeType": "application/x-myformat", "Description": "Custom Format" }, "Signature": [ {"Offset": 0, "Pattern": "4D 59 46 4D 54"} ] } ### Response #### Success Response (200) - **Status** (String) - Confirmation of definition registration. ``` -------------------------------- ### Inspect Content and Process Results Source: https://github.com/mediatedcommunications/mime-detective/blob/main/README.md Shows how to perform file inspection on various input types and how to group the resulting identification data by file extension or MIME type. ```csharp var Results = Inspector.Inspect(ContentByteArray); var Results = Inspector.Inspect(ContentStream); var Results = Inspector.Inspect(ContentFileName); var ResultsByFileExtension = Results.ByFileExtension(); var ResultsByMimeType = Results.ByMimeType(); ``` -------------------------------- ### Create Custom File Type Detection Rules with Mime-Detective Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt This C# code demonstrates how to create custom file type definitions for Mime-Detective. It shows how to add predefined definitions, create new definitions using `PrefixSegment` for offset-based signatures and `StringSegment` for pattern-based signatures, and build an inspector with these custom definitions. Dependencies include the MimeDetective library. ```csharp using MimeDetective; using MimeDetective.Definitions; using MimeDetective.Storage; using System.Collections.Immutable; // Create custom definitions list var customDefinitions = new List(); // Add predefined definitions customDefinitions.AddRange(DefaultDefinitions.FileTypes.Audio.MP3()); customDefinitions.AddRange(DefaultDefinitions.FileTypes.Images.All()); // Add a custom file type with prefix-based signature customDefinitions.Add(new Definition { File = new FileType { Extensions = ["myformat", "mfmt"], MimeType = "application/x-myformat", Description = "My Custom File Format", Categories = [Category.Document, Category.Compressed] }, Signature = new Segment[] { PrefixSegment.Create(0, "4D 59 46 4D 54"), // "MYFMT" at offset 0 PrefixSegment.Create(5, "01 00") // Version bytes at offset 5 }.ToSignature() }); // Add a custom file type with string-based signature (can appear anywhere) customDefinitions.Add(new Definition { File = new FileType { Extensions = ["magic"], MimeType = "application/x-magic", Description = "Magic File", Categories = [Category.Other] }, Signature = new Segment[] { StringSegment.Create("MAGIC_HEADER"), // This string anywhere in file PrefixSegment.Create(0, "00 00 00 01") // Combined with prefix at start }.ToSignature() }); // Build inspector with custom definitions var inspector = new ContentInspectorBuilder { Definitions = customDefinitions, StringSegmentOptions = new() { OptimizeFor = MimeDetective.Engine.StringSegmentResourceOptimization.HighSpeed } }.Build(); // Use the inspector var results = inspector.Inspect("/path/to/file.myformat"); ``` -------------------------------- ### Group Detection Results by File Extension and MIME Type Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt Demonstrates how to group the results of file content inspection by their file extension or MIME type. The results are aggregated by points and sorted in descending order. It also shows how to retrieve the most likely extension or MIME type from the grouped results. ```csharp using MimeDetective; using MimeDetective.Definitions; var inspector = new ContentInspectorBuilder { Definitions = DefaultDefinitions.All() }.Build(); var results = inspector.Inspect("/path/to/unknown-file"); // Group results by file extension var byExtension = results.ByFileExtension(); foreach (var ext in byExtension) { Console.WriteLine($"Extension: .{ext.Extension}"); Console.WriteLine($"Total Points: {ext.Points}"); Console.WriteLine($"Number of Matching Definitions: {ext.Matches.Length}"); } // Get the most likely file extension var bestExtension = byExtension.FirstOrDefault()?.Extension; Console.WriteLine($"Most likely extension: .{bestExtension}"); // Group results by MIME type var byMimeType = results.ByMimeType(); foreach (var mime in byMimeType) { Console.WriteLine($"MIME Type: {mime.MimeType}"); Console.WriteLine($"Total Points: {mime.Points}"); } // Get the most likely MIME type var bestMimeType = byMimeType.FirstOrDefault()?.MimeType; Console.WriteLine($"Most likely MIME type: {bestMimeType}"); ``` -------------------------------- ### Accessing Default Definitions Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt This snippet shows how to retrieve all built-in file type definitions, definitions categorized by type (e.g., Archives, Audio, Images), and specific file type definitions. ```APIDOC ## Accessing Default Definitions ### Description This section demonstrates how to access the built-in Default definition pack provided by Mime-Detective. You can retrieve all definitions, filter them by category, or select specific file types. ### Method N/A (Code Example) ### Endpoint N/A (Code Example) ### Parameters N/A ### Request Example ```csharp using MimeDetective; using MimeDetective.Definitions; // Get all default definitions var allDefaults = DefaultDefinitions.All(); // Get definitions by category var archiveDefinitions = DefaultDefinitions.FileTypes.Archives.All(); // 7z, bz2, gz, rar, tar, zip var audioDefinitions = DefaultDefinitions.FileTypes.Audio.All(); // flac, m4a, mid, mp3, ogg, wav var imageDefinitions = DefaultDefinitions.FileTypes.Images.All(); // bmp, gif, ico, jpg, png, psd, tiff, webp var documentDefinitions = DefaultDefinitions.FileTypes.Documents.All(); // doc, docx, pdf, ppt, pptx, xls, xlsx var videoDefinitions = DefaultDefinitions.FileTypes.Video.All(); // 3gp, flv, mov, mp4 var executableDefinitions = DefaultDefinitions.FileTypes.Executables.All(); // dll, exe, elf, coff var emailDefinitions = DefaultDefinitions.FileTypes.Email.All(); // eml, pst var textDefinitions = DefaultDefinitions.FileTypes.Text.All(); // txt var xmlDefinitions = DefaultDefinitions.FileTypes.Xml.All(); // xml // Get specific file type definitions var mp3Only = DefaultDefinitions.FileTypes.Audio.MP3(); var jpegOnly = DefaultDefinitions.FileTypes.Images.JPEG(); var pngOnly = DefaultDefinitions.FileTypes.Images.PNG(); var tiffAll = DefaultDefinitions.FileTypes.Images.TIFF(); // All TIFF variants ``` ### Response N/A (Code Example) ### Response Example N/A (Code Example) ``` -------------------------------- ### Optimize Mime-Detective Definition Memory Usage Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt This C# code illustrates how to reduce the memory footprint of Mime-Detective definitions. It demonstrates using `ScopeExtensions` to filter definitions by file extensions and various `Trim*` methods to remove metadata like descriptions, MIME types, and categories. Dependencies include the MimeDetective library. ```csharp using MimeDetective; using MimeDetective.Definitions; using MimeDetective.Storage; using System.Collections.Immutable; // Load all definitions var allDefinitions = new Definitions.ExhaustiveBuilder { UsageType = Definitions.Licensing.UsageType.PersonalNonCommercial }.Build(); // Limit to only audio file extensions var audioExtensions = new[] { "aif", "cda", "mid", "midi", "mp3", "mpa", "ogg", "wav", "wma", "wpl", "flac" }.ToImmutableHashSet(StringComparer.InvariantCultureIgnoreCase); // Scope and trim definitions for minimal memory usage var optimizedDefinitions = allDefinitions .ScopeExtensions(audioExtensions) // Only keep definitions matching these extensions .TrimMeta() // Remove author, creation date, etc. .TrimDescription() // Remove file type descriptions .TrimMimeType() // Remove MIME types (if not needed) .TrimCategories() // Remove category information .ToImmutableArray(); Console.WriteLine($"Original definitions: {allDefinitions.Length}"); Console.WriteLine($"Optimized definitions: {optimizedDefinitions.Length}"); // Build optimized inspector var inspector = new ContentInspectorBuilder { Definitions = optimizedDefinitions, Parallel = false // Fewer definitions = less benefit from parallelization }.Build(); // Deduplicate definitions to share common strings (further memory optimization) var deduplicationResult = allDefinitions.Deduplicate(); var deduplicatedDefinitions = deduplicationResult.Definitions; var deduplicatedInspector = new ContentInspectorBuilder { Definitions = deduplicatedDefinitions }.Build(); ``` -------------------------------- ### Optimize ContentInspector Performance Source: https://github.com/mediatedcommunications/mime-detective/blob/main/README.md Optimizes memory and speed by scoping the definition set to specific extensions and trimming unnecessary metadata like descriptions and MIME types. ```csharp var Extensions = new[]{ "aif", "cda","mid", "midi","mp3", "mpa", "ogg","wav","wma", "wpl" }.ToImmutableHashSet(StringComparer.InvariantCultureIgnoreCase); var ScopedDefinitions = AllDefinitions .ScopeExtensions(Extensions) .TrimMeta() .TrimDescription() .TrimMimeType() .ToImmutableArray(); var Inspector = new ContentInspectorBuilder() { Definitions = ScopedDefinitions, }.Build(); ``` -------------------------------- ### ASP.NET Core Integration for File Upload Type Detection Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt Integrates Mime-Detective into an ASP.NET Core Minimal API to detect uploaded file types. It includes endpoints for detecting the MIME type of uploaded content and validating file extensions. The code utilizes `ContentInspectorBuilder` for inspection and `MemoryPool` for efficient buffer management. ```csharp using Microsoft.AspNetCore.Mvc; using MimeDetective; using MimeDetective.Definitions; using MimeDetective.Engine; using System.Buffers; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); // Create inspector once at startup (expensive operation) var inspector = new ContentInspectorBuilder { Definitions = DefaultDefinitions.All() }.Build(); // Endpoint to detect file type from uploaded content // Test with: curl --data-binary @example.jpg http://localhost:5000/detect app.MapPost("/detect", async ([FromHeader(Name = "Content-Length")] int length, Stream stream) => { if (length <= 0) { return Results.BadRequest("Invalid Content-Length"); } if (length > 10 * 1024 * 1024) { return Results.BadRequest("File too large (max 10MB)"); } // Rent buffer from pool for efficiency using var buffer = MemoryPool.Shared.Rent(length); await stream.ReadExactlyAsync(buffer.Memory[..length]); // Inspect content var results = inspector.Inspect(buffer.Memory[..length].Span); // Return detected types var detectedTypes = results .Where(m => m.Type == DefinitionMatchType.Complete) .OrderByDescending(m => m.Points) .Select(m => new { MimeType = m.Definition.File.MimeType, Extensions = m.Definition.File.Extensions.ToArray(), Confidence = m.Points }) .ToList(); return Results.Ok(detectedTypes); }); // Endpoint to validate file type matches expected type app.MapPost("/validate/{expectedExtension}", async ( string expectedExtension, [FromHeader(Name = "Content-Length")] int length, Stream stream) => { using var buffer = MemoryPool.Shared.Rent(Math.Min(length, 8192)); // Only need header var bytesRead = await stream.ReadAsync(buffer.Memory[..Math.Min(length, 8192)]); var results = inspector.Inspect(buffer.Memory[..bytesRead].Span); var byExtension = results.ByFileExtension(); var isValid = byExtension.Any(e => e.Extension.Equals(expectedExtension.TrimStart('.'), StringComparison.OrdinalIgnoreCase)); return Results.Ok(new { Valid = isValid, ExpectedExtension = expectedExtension, DetectedExtension = byExtension.FirstOrDefault()?.Extension }); }); app.Run(); ``` -------------------------------- ### Accessing Default File Type Definitions in C# Source: https://context7.com/mediatedcommunications/mime-detective/llms.txt This snippet demonstrates how to retrieve built-in file type definitions using the DefaultDefinitions class. It covers accessing all definitions, filtering by category, and creating a custom ContentInspector with a specific subset of definitions. ```csharp using MimeDetective; using MimeDetective.Definitions; // Get all default definitions var allDefaults = DefaultDefinitions.All(); // Get definitions by category var archiveDefinitions = DefaultDefinitions.FileTypes.Archives.All(); var audioDefinitions = DefaultDefinitions.FileTypes.Audio.All(); var imageDefinitions = DefaultDefinitions.FileTypes.Images.All(); var documentDefinitions = DefaultDefinitions.FileTypes.Documents.All(); var videoDefinitions = DefaultDefinitions.FileTypes.Video.All(); var executableDefinitions = DefaultDefinitions.FileTypes.Executables.All(); var emailDefinitions = DefaultDefinitions.FileTypes.Email.All(); var textDefinitions = DefaultDefinitions.FileTypes.Text.All(); var xmlDefinitions = DefaultDefinitions.FileTypes.Xml.All(); // Get specific file type definitions var mp3Only = DefaultDefinitions.FileTypes.Audio.MP3(); var jpegOnly = DefaultDefinitions.FileTypes.Images.JPEG(); var pngOnly = DefaultDefinitions.FileTypes.Images.PNG(); var tiffAll = DefaultDefinitions.FileTypes.Images.TIFF(); // Combine specific definitions for a focused inspector var imageAudioInspector = new ContentInspectorBuilder { Definitions = [ .. DefaultDefinitions.FileTypes.Images.All(), .. DefaultDefinitions.FileTypes.Audio.All() ] }.Build(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.