### Development Setup and Testing
Source: https://github.com/ajmitev/filetypechecker/blob/master/README.md
Provides commands for cloning the repository, restoring dependencies, building the project, and running tests.
```bash
git clone https://github.com/AJMitev/FileTypeChecker.git
cd FileTypeChecker
dotnet restore
dotnet build
dotnet test
```
--------------------------------
### Install FileTypeChecker NuGet Package
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Install the File.TypeChecker NuGet package using the .NET CLI, Package Manager, or by adding a PackageReference to your .csproj file.
```bash
# .NET CLI
dotnet add package File.TypeChecker
# Package Manager
Install-Package File.TypeChecker
# PackageReference in .csproj
#
```
--------------------------------
### Implement a New File Type
Source: https://github.com/ajmitev/filetypechecker/blob/master/CONTRIBUTING.md
Example of creating a new file type by inheriting from `FileType`. Implement `IsMatch` and `IsMatchAsync` for validation.
```csharp
public class MyFileType : FileType
{
public override string Name => "My File Format";
public override string[] Extensions => new[] { "myf" };
public override bool IsMatch(ReadOnlySpan data)
{
// Implementation
}
public override async Task IsMatchAsync(Stream stream, CancellationToken cancellationToken = default)
{
// Async implementation
}
}
```
--------------------------------
### Install FileTypeChecker via Package Manager
Source: https://github.com/ajmitev/filetypechecker/blob/master/README.md
Use this command in the Package Manager Console to install the File.TypeChecker NuGet package.
```powershell
Install-Package File.TypeChecker
```
--------------------------------
### Install FileTypeChecker via .NET CLI
Source: https://github.com/ajmitev/filetypechecker/blob/master/README.md
Use this command in your project directory to add the File.TypeChecker NuGet package using the .NET CLI.
```bash
dotnet add package File.TypeChecker
```
--------------------------------
### Basic File Type Detection Example
Source: https://github.com/ajmitev/filetypechecker/blob/master/README.md
Shows how to open a file stream and use FileTypeValidator to determine if its type is recognizable and to retrieve its name and extension. Requires importing the FileTypeChecker namespace.
```csharp
using FileTypeChecker;
using (var fileStream = File.OpenRead("document.pdf"))
{
// Check if file type is recognizable
if (FileTypeValidator.IsTypeRecognizable(fileStream))
{
// Get file type information
IFileType fileType = FileTypeValidator.GetFileType(fileStream);
Console.WriteLine($"Type: {fileType.Name}");
Console.WriteLine($"Extension: {fileType.Extension}");
}
}
```
--------------------------------
### Implement Custom File Type with Single Magic Bytes
Source: https://github.com/ajmitev/filetypechecker/wiki/Create-custom-type
Example implementation of a custom file type inheriting from FileType, using a single byte array for identification.
```csharp
using FileTypeChecker.Abstracts;
public class MyCustomFileType : FileType
{
private static readonly string name = "My Super Cool Custom Type 1.0";
private static readonly string extension = "ext";
private static readonly byte[] magicBytes = new byte[] { 0xAF };
public MyCustomFileType() : base(name, extension, magicBytes){}
}
```
--------------------------------
### Magic Number Examples
Source: https://github.com/ajmitev/filetypechecker/blob/master/README.md
Illustrates common magic numbers for various file types. These byte sequences are used by the library to identify file formats regardless of their extension.
```text
PDF: 25 50 44 46 (%PDF)
PNG: 89 50 4E 47 (‰PNG)
JPEG: FF D8 FF (ÿØÿ)
ZIP: 50 4B 03 04 (PK..)
```
--------------------------------
### Identify Exact File Type
Source: https://github.com/ajmitev/filetypechecker/wiki/How-to-use?
Get the exact file type of a file. Throws an exception if the file type is not recognizable. Requires opening a file stream.
```csharp
using var fileStream = File.OpenRead(filePath);
var isRecognizableType = FileTypeValidator.IsTypeRecognizable(fileStream);
if (!isRecognizableType)
{
throw new InvalidDataException("Invalid file type!");
}
IFileType fileType = FileTypeValidator.GetFileType(fileStream);
```
--------------------------------
### Implement Custom File Type with Multiple Magic Bytes
Source: https://github.com/ajmitev/filetypechecker/wiki/Create-custom-type
Example implementation of a custom file type inheriting from FileType, using a jagged array of byte arrays for identification, suitable for types with multiple versions or variations.
```csharp
using FileTypeChecker.Abstracts;
public class MyCustomFileTypeWithManyVersions : FileType
{
private static readonly string name = "My Super Cool Custom Type 1.0";
private static readonly string extension = "ext2";
private static readonly byte[][] magicBytes = { new byte[] { 0xAF }, new byte[] { 0xEF } };
public MyCustomFileTypeWithManyVersions() : base(name, extension, magicBytes ){}
}
```
--------------------------------
### Quick Start File Type Detection
Source: https://github.com/ajmitev/filetypechecker/blob/master/README.md
Demonstrates basic file type validation and identification using FileTypeValidator. Ensure the file stream is open and readable. This snippet checks if a type is recognizable and retrieves its name and extension.
```csharp
using (var fileStream = File.OpenRead("suspicious-file.exe"))
{
// Check if file type can be identified
if (FileTypeValidator.IsTypeRecognizable(fileStream))
{
// Get the actual file type
IFileType fileType = FileTypeValidator.GetFileType(fileStream);
Console.WriteLine($"File type: {fileType.Name} ({fileType.Extension})");
// Check specific type
bool isImage = fileStream.IsImage();
bool isPdf = fileStream.Is();
}
}
```
--------------------------------
### Exception-Safe File Type Retrieval
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Use `TryGetFileType` to get a `MatchResult` object, avoiding exceptions for unknown file types. Check `result.HasMatch` before accessing `result.Type`. This is recommended for untrusted input.
```csharp
using FileTypeChecker;
using var stream = File.OpenRead("suspicious-file");
MatchResult result = FileTypeValidator.TryGetFileType(stream);
if (result.HasMatch)
{
Console.WriteLine($"Detected: {result.Type.Name} (.{result.Type.Extension})");
Console.WriteLine($"MIME: {result.Type.MimeType}");
}
else
{
Console.WriteLine("File type could not be determined.");
}
// Async version
using var asyncStream = File.OpenRead("suspicious-file");
MatchResult asyncResult = await FileTypeValidator.TryGetFileTypeAsync(asyncStream);
Console.WriteLine(asyncResult.HasMatch ? asyncResult.Type.Name : "No match");
// ReadOnlySpan overload
byte[] bytes = File.ReadAllBytes("suspicious-file");
MatchResult spanResult = FileTypeValidator.TryGetFileType(bytes.AsSpan());
```
--------------------------------
### ASP.NET Core File Upload Validation with FileTypeChecker
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Integrate FileTypeChecker into ASP.NET Core controllers to validate `IFormFile` uploads based on content, not just filename. This example demonstrates blocking executable content, ensuring image formats, and checking against an allowed list of image extensions.
```csharp
using FileTypeChecker;
using FileTypeChecker.Extensions;
using FileTypeChecker.Types;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class UploadController : ControllerBase
{
private static readonly string[] AllowedImageExtensions = { "jpg", "png", "gif", "bmp" };
[HttpPost("avatar")]
public async Task UploadAvatar(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest("No file provided.");
await using var stream = file.OpenReadStream();
// Block any executable content regardless of file extension
if (stream.IsExecutable())
return StatusCode(403, "Executable files are not permitted.");
// Ensure it is an image by binary content
if (!stream.IsImage())
return BadRequest("Only image files are accepted.");
// Confirm the specific format is in our allowed list
MatchResult match = FileTypeValidator.TryGetFileType(stream);
if (!match.HasMatch || !AllowedImageExtensions.Contains(match.Type.Extension))
return BadRequest($"Unsupported image format. Allowed: {string.Join(", ", AllowedImageExtensions)}");
Console.WriteLine($"Accepted upload: {match.Type.Name} ({match.Type.MimeType})");
// → Accepted upload: Portable Network Graphic (image/png)
// Save file...
return Ok(new { type = match.Type.Name, extension = match.Type.Extension });
}
[HttpPost("document")]
public async Task UploadDocument(IFormFile file)
{
await using var stream = file.OpenReadStream();
// Async content-based check
bool isDoc = await FileTypeValidator.IsDocumentAsync(stream);
if (!isDoc)
return BadRequest("Only document files (PDF, DOCX, XLSX, XML) are accepted.");
IFileType docType = await FileTypeValidator.GetFileTypeAsync(stream);
return Ok(new { name = docType.Name, mime = docType.MimeType });
}
}
```
--------------------------------
### Get File Type Information with FileTypeChecker
Source: https://github.com/ajmitev/filetypechecker/wiki/Home
Use this snippet to open a file stream and retrieve its recognized type, extension, and check if it's an image or a specific image type like Bitmap. Ensure the file stream is properly disposed of.
```csharp
using (var fileStream = File.OpenRead("myFileLocation"))
{
var isRecognizableType = FileTypeValidator.IsTypeRecognizable(fileStream);
if (!isRecognizableType)
{
// Do something ...
}
IFileType fileType = FileTypeValidator.GetFileType(fileStream);
Console.WriteLine("Type Name: {0}", fileType.Name);
Console.WriteLine("Type Extension: {0}", fileType.Extension);
Console.WriteLine("Is Image?: {0}", fileStream.IsImage());
Console.WriteLine("Is Bitmap?: {0}", fileStream.Is());
}
```
--------------------------------
### Run Sample Application
Source: https://github.com/ajmitev/filetypechecker/blob/master/CONTRIBUTING.md
Navigate to the sample application directory and run it using the dotnet CLI. This allows testing the library in a practical scenario.
```bash
cd Samples/FileTypeChecker.App
dotnet run
```
--------------------------------
### Clone and Navigate Repository
Source: https://github.com/ajmitev/filetypechecker/blob/master/CONTRIBUTING.md
Clone the repository and navigate into the project directory to begin development.
```bash
git clone https://github.com/yourusername/FileTypeChecker.git
cd FileTypeChecker
```
--------------------------------
### Build the Project
Source: https://github.com/ajmitev/filetypechecker/blob/master/CONTRIBUTING.md
Build the .NET project using the dotnet CLI. This command compiles the library and any associated projects.
```bash
dotnet build
```
--------------------------------
### Register Custom File Type
Source: https://github.com/ajmitev/filetypechecker/blob/master/README.md
Demonstrates how to define and register a custom file type with its own signature matching logic.
```csharp
// Register your own file type
public class MyCustomType : FileType
{
public override string Name => "My Custom Format";
public override string Extension => "mycustom";
public override string MimeType => "application/x-mycustom";
public override bool IsMatch(byte[] signature, Stream stream)
{
return signature.Length >= 4 &&
signature[0] == 0x4D && signature[1] == 0x59 &&
signature[2] == 0x43 && signature[3] == 0x54;
}
}
// Use it
FileTypeValidator.RegisterType();
```
--------------------------------
### Run All Tests
Source: https://github.com/ajmitev/filetypechecker/blob/master/CONTRIBUTING.md
Execute all unit tests in the project to ensure code integrity. This is a crucial step before submitting changes.
```bash
dotnet test
```
--------------------------------
### FileType Constructor with Single Magic Bytes
Source: https://github.com/ajmitev/filetypechecker/wiki/Create-custom-type
Use this constructor when your custom file type is identified by a single array of bytes.
```csharp
public FileType(string name, string extension, byte[] magicBytes){}
```
--------------------------------
### FileType Constructor with Jagged Array of Magic Bytes
Source: https://github.com/ajmitev/filetypechecker/wiki/Create-custom-type
Use this constructor when your custom file type can be identified by multiple, distinct byte arrays, useful for grouping types or handling variations.
```csharp
public FileType(string name, string extension, byte[][] magicBytesJaggedArray){}
```
--------------------------------
### Add FileTypeChecker via PackageReference
Source: https://github.com/ajmitev/filetypechecker/blob/master/README.md
Include this XML snippet in your project file to add the File.TypeChecker NuGet package as a dependency.
```xml
```
--------------------------------
### ASP.NET Core Model Binding with File Validation
Source: https://github.com/ajmitev/filetypechecker/blob/master/README.md
Shows how to use pre-built validation attributes for file uploads in ASP.NET Core models, including allowed types and maximum file size.
```csharp
public class UploadModel
{
[AllowedFileTypes(FileType.Jpeg, FileType.Png)]
[MaxFileSize(5 * 1024 * 1024)] // 5MB
public IFormFile ProfileImage { get; set; }
}
```
--------------------------------
### Category Checks: IsDocument and IsExecutable
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Use `IsDocument` for PDF, Office, and XML files, and `IsExecutable` for Windows PE executables and ELF binaries. Both are available as static and extension methods, including async variants, and are useful for security checks.
```csharp
using FileTypeChecker;
using FileTypeChecker.Extensions;
// Document check
using var docStream = File.OpenRead("report.docx");
bool isDoc = docStream.IsDocument();
Console.WriteLine($"Is Document: {isDoc}"); // Is Document: True
// Executable check — useful for blocking EXE uploads
using var exeStream = File.OpenRead("setup.exe");
bool isExe = exeStream.IsExecutable();
Console.WriteLine($"Is Executable: {isExe}"); // Is Executable: True
// Async variants
bool isDocAsync = await FileTypeValidator.IsDocumentAsync(docStream);
bool isExeAsync = await FileTypeValidator.IsExecutableAsync(exeStream);
// Block executables in a file upload handler
public IActionResult Upload(IFormFile file)
{
using var stream = file.OpenReadStream();
if (stream.IsExecutable())
return BadRequest("Executable files are not allowed.");
// proceed with safe upload
}
```
--------------------------------
### Check for General File Types (Image, Archive)
Source: https://github.com/ajmitev/filetypechecker/wiki/How-to-use?
Easily check if a file belongs to general categories like images or archives using provided extension methods or static methods.
```csharp
using FileTypeChecker.Extensions;
bool isImage = fileStream.IsImage();
bool isArchive = fileStream.IsArchive();
```
```csharp
bool isImage = FileTypeValidator.IsImage(fileStream);
bool isArchive = FileTypeValidator.IsArchive(fileStream);
```
--------------------------------
### Retrieve Full File Type Details
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Use `GetFileType` to obtain an `IFileType` object with details like Name, Extension, and MimeType. This method throws `TypeNotFoundException` if the type is not recognized. Consider `TryGetFileType` for safer handling of untrusted input.
```csharp
using FileTypeChecker;
using FileTypeChecker.Abstracts;
using var fileStream = File.OpenRead("photo.jpg");
// Throws TypeNotFoundException if unrecognized
IFileType fileType = FileTypeValidator.GetFileType(fileStream);
Console.WriteLine($"Name: {fileType.Name}"); // Joint Photographic Experts Group
Console.WriteLine($"Extension: {fileType.Extension}"); // jpg
Console.WriteLine($"MIME: {fileType.MimeType}"); // image/jpeg
// From byte array
byte[] bytes = File.ReadAllBytes("photo.jpg");
IFileType typeFromBytes = FileTypeValidator.GetFileType(bytes);
// High-performance span overload
IFileType typeFromSpan = FileTypeValidator.GetFileType(bytes.AsSpan());
// Async
using var asyncStream = File.OpenRead("photo.jpg");
IFileType asyncType = await FileTypeValidator.GetFileTypeAsync(asyncStream);
```
--------------------------------
### Register Custom File Types with FileTypeValidator
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Define custom file types by implementing `FileType` and register them using `FileTypeValidator.RegisterCustomTypes`. This method scans an assembly for non-abstract classes implementing `IFileType` and must be called once at application startup. Custom types are discovered via reflection.
```csharp
using FileTypeChecker.Abstracts;
public class FlatBuffers : FileType
{
private static readonly string TypeName = "FlatBuffers Binary";
private static readonly string TypeExtension = "fbs";
private static readonly string TypeMimeType = "application/x-flatbuffers";
// FlatBuffers files begin with a 4-byte root table offset (variable),
// but many implementations prefix with a known file identifier: "BFBS"
private static readonly byte[] MagicBytes = new byte[] { 0x42, 0x46, 0x42, 0x53 }; // BFBS
public FlatBuffers() : base(TypeName, TypeMimeType, TypeExtension, MagicBytes) { }
}
// Type with multiple magic byte variants (e.g., two format versions)
public class LegacyData : FileType
{
private static readonly byte[][] AllMagicBytes = {
new byte[] { 0x4C, 0x44, 0x01 }, // Version 1
new byte[] { 0x4C, 0x44, 0x02 } // Version 2
};
public LegacyData() : base("Legacy Data", "application/x-legacy", "ld", AllMagicBytes) { }
}
```
```csharp
// 2. Register at application startup
// In Program.cs (.NET 6+):
FileTypeValidator.RegisterCustomTypes(typeof(FlatBuffers).Assembly);
// 3. Use the custom type like any built-in type
using var stream = File.OpenRead("data.fbs");
bool isFbs = FileTypeValidator.Is(stream);
MatchResult result = FileTypeValidator.TryGetFileType(stream);
Console.WriteLine(result.Type?.Name); // FlatBuffers Binary
```
--------------------------------
### Category-Based and Specific Type Validation
Source: https://github.com/ajmitev/filetypechecker/blob/master/README.md
Demonstrates how to validate file types based on categories like images, documents, or archives, and how to check for specific types using generic methods. This requires the file stream to be open and readable.
```csharp
using (var fileStream = File.OpenRead("image.jpg"))
{
// Check by category
bool isImage = fileStream.IsImage();
bool isDocument = fileStream.IsDocument();
bool isArchive = fileStream.IsArchive();
// Check specific type
bool isPng = fileStream.Is();
bool isJpeg = fileStream.Is();
}
```
--------------------------------
### Check if File Type is Recognizable
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Use `IsTypeRecognizable` to determine if the binary content of a file matches any known signature. Accepts Stream, byte[], or ReadOnlySpan. Use the async version for non-blocking operations.
```csharp
using FileTypeChecker;
// From a file stream
using var fileStream = File.OpenRead("upload.bin");
bool recognized = FileTypeValidator.IsTypeRecognizable(fileStream);
Console.WriteLine(recognized ? "Known file type" : "Unknown file type");
// Output: Known file type
// From a byte array
byte[] fileBytes = File.ReadAllBytes("upload.bin");
bool recognizedFromBytes = FileTypeValidator.IsTypeRecognizable(fileBytes);
// From a ReadOnlySpan (zero allocation, high-performance)
ReadOnlySpan span = fileBytes.AsSpan();
bool recognizedFromSpan = FileTypeValidator.IsTypeRecognizable(span);
// Async version
using var asyncStream = File.OpenRead("upload.bin");
bool recognizedAsync = await FileTypeValidator.IsTypeRecognizableAsync(asyncStream);
```
--------------------------------
### Register Custom File Types in C#
Source: https://github.com/ajmitev/filetypechecker/wiki/What-types-of-file-are-supported?
Use this code in your application's configuration to register custom file types. Ensure that the custom type class is defined in the specified assembly.
```csharp
FileTypeValidator.RegisterCustomTypes(typeof(MyCustomFileType).Assembly);
```
--------------------------------
### Check if File is a Specific Type (Bitmap)
Source: https://github.com/ajmitev/filetypechecker/wiki/How-to-use?
Verify if a file is of a specific type, such as Bitmap. This can be done using the static method or an extension method on the file stream.
```csharp
using FileTypeChecker.Types;
bool isBitmap = FileTypeValidator.Is(fileStream);
```
```csharp
using FileTypeChecker.Types;
using FileTypeChecker.Extensions;
bool isBitmap = fileStream.Is();
```
--------------------------------
### FileTypeValidator.TryGetFileType
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Provides an exception-safe way to retrieve file type information. It returns a `MatchResult` object, allowing you to check for a match via `result.HasMatch` before accessing the `result.Type` property. This is recommended for untrusted input. Asynchronous and ReadOnlySpan overloads are available.
```APIDOC
## TryGetFileType
### Description
Returns a `MatchResult` object instead of throwing an exception when a file type cannot be determined. This method is recommended for handling untrusted input.
### Method
`FileTypeValidator.TryGetFileType(Stream input)`
`FileTypeValidator.TryGetFileType(byte[] input)`
`FileTypeValidator.TryGetFileType(ReadOnlySpan input)`
`await FileTypeValidator.TryGetFileTypeAsync(Stream input)`
### Parameters
#### Input
- **input** (Stream | byte[] | ReadOnlySpan) - Required - The binary data to analyze.
### Request Example
```csharp
using var stream = File.OpenRead("suspicious-file");
MatchResult result = FileTypeValidator.TryGetFileType(stream);
if (result.HasMatch)
{
Console.WriteLine($"Detected: {result.Type.Name}");
}
using var asyncStream = File.OpenRead("suspicious-file");
MatchResult asyncResult = await FileTypeValidator.TryGetFileTypeAsync(asyncStream);
byte[] bytes = File.ReadAllBytes("suspicious-file");
MatchResult spanResult = FileTypeValidator.TryGetFileType(bytes.AsSpan());
```
### Response
- **MatchResult** - An object containing the result of the file type detection:
- **HasMatch** (bool) - `true` if a file type was successfully matched, `false` otherwise.
- **Type** (IFileType) - The detected file type details (available only if `HasMatch` is `true`). Contains `Name`, `Extension`, and `MimeType`.
### Error Handling
- Does not throw exceptions on unrecognized file types; returns `MatchResult` with `HasMatch` set to `false`.
```
--------------------------------
### FileTypeValidator.IsArchive
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Checks if the file is any supported archive format. Supports static, extension, byte array, and asynchronous methods.
```APIDOC
## `FileTypeValidator.IsArchive` — Category check for archives
Returns `true` if the file is any supported archive format: ZIP, RAR, 7-Zip, TAR, GZIP, BZIP2, LZIP, XZ, or extensible archive (XAR). Available in all input and async variants.
### Usage
```csharp
using FileTypeChecker;
using FileTypeChecker.Extensions;
using var stream = File.OpenRead("backup.tar.gz");
bool isArchive = FileTypeValidator.IsArchive(stream);
Console.WriteLine($"Is Archive: {isArchive}"); // Is Archive: True
// Extension method
bool isArchiveExt = stream.IsArchive();
// Byte array
byte[] bytes = File.ReadAllBytes("backup.tar.gz");
bool isArchiveBytes = bytes.IsArchive();
// Async
using var asyncStream = File.OpenRead("backup.tar.gz");
bool isArchiveAsync = await FileTypeValidator.IsArchiveAsync(asyncStream);
```
```
--------------------------------
### Run Async Tests Only
Source: https://github.com/ajmitev/filetypechecker/blob/master/CONTRIBUTING.md
Filter and run only the asynchronous tests. This is useful for focusing on async-related issues or performance.
```bash
dotnet test --filter "FileTypeValidatorAsyncTests|StreamExtensionsAsyncTests"
```
--------------------------------
### Check if File Type is Recognizable
Source: https://github.com/ajmitev/filetypechecker/wiki/How-to-use?
Use this method to determine if FileTypeChecker can identify the type of a given file. Requires opening a file stream.
```csharp
using var fileStream = File.OpenRead(filePath);
var isRecognizableType = FileTypeValidator.IsTypeRecognizable(fileStream);
```
--------------------------------
### Check if File is an Archive with FileTypeValidator.IsArchive
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Use `FileTypeValidator.IsArchive` to check if a file is a supported archive format. This method is available in static, extension (for stream, byte[], ReadOnlySpan), and asynchronous forms.
```csharp
using FileTypeChecker;
using FileTypeChecker.Extensions;
using var stream = File.OpenRead("backup.tar.gz");
bool isArchive = FileTypeValidator.IsArchive(stream);
Console.WriteLine($"Is Archive: {isArchive}"); // Is Archive: True
// Extension method
bool isArchiveExt = stream.IsArchive();
// Byte array
byte[] bytes = File.ReadAllBytes("backup.tar.gz");
bool isArchiveBytes = bytes.IsArchive();
// Async
using var asyncStream = File.OpenRead("backup.tar.gz");
bool isArchiveAsync = await FileTypeValidator.IsArchiveAsync(asyncStream);
```
--------------------------------
### Validate Uploaded Image File
Source: https://github.com/ajmitev/filetypechecker/blob/master/README.md
Validates if an uploaded file is an image and checks if its type is among the allowed formats (PNG, JPEG, BMP).
```csharp
public bool ValidateUploadedFile(IFormFile file)
{
using (var stream = file.OpenReadStream())
{
// Verify file is actually an image (regardless of file extension)
if (!stream.IsImage())
{
throw new InvalidOperationException("Only image files are allowed");
}
// Additional validation for specific formats
var fileType = FileTypeValidator.GetFileType(stream);
var allowedTypes = new[] { "PNG", "JPEG", "BMP" };
return allowedTypes.Contains(fileType.Name);
}
}
```
--------------------------------
### Validate Specific File Type with FileTypeValidator.Is
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Use `FileTypeValidator.Is` to check if a stream or byte array matches a specific file type. Ensure the generic type `T` inherits `FileType` and implements `IFileType`. Extension and async methods are also available.
```csharp
using FileTypeChecker;
using FileTypeChecker.Types;
using var stream = File.OpenRead("document.pdf");
// Static method form
bool isPdf = FileTypeValidator.Is(stream);
bool isPng = FileTypeValidator.Is(stream);
bool isZip = FileTypeValidator.Is(stream);
bool isDocx = FileTypeValidator.Is(stream);
Console.WriteLine($"Is PDF: {isPdf}"); // Is PDF: True
// Extension method form (requires: using FileTypeChecker.Extensions)
bool isPdfExt = stream.Is();
// Byte array form
byte[] bytes = File.ReadAllBytes("document.pdf");
bool isPdfBytes = FileTypeValidator.Is(bytes);
// Async form
using var asyncStream = File.OpenRead("document.pdf");
bool isPdfAsync = await FileTypeValidator.IsAsync(asyncStream);
```
--------------------------------
### FileTypeValidator.Is
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Checks if the file content matches one exact file type. Supports static, extension, byte array, and asynchronous methods.
```APIDOC
## `FileTypeValidator.Is` — Validate against a specific type
Checks whether the file content matches one exact file type. The generic type parameter `T` must inherit `FileType` and implement `IFileType`. All built-in types are found in the `FileTypeChecker.Types` namespace.
### Usage
```csharp
using FileTypeChecker;
using FileTypeChecker.Types;
using var stream = File.OpenRead("document.pdf");
// Static method form
bool isPdf = FileTypeValidator.Is(stream);
bool isPng = FileTypeValidator.Is(stream);
bool isZip = FileTypeValidator.Is(stream);
bool isDocx = FileTypeValidator.Is(stream);
Console.WriteLine($"Is PDF: {isPdf}"); // Is PDF: True
// Extension method form (requires: using FileTypeChecker.Extensions)
bool isPdfExt = stream.Is();
// Byte array form
byte[] bytes = File.ReadAllBytes("document.pdf");
bool isPdfBytes = FileTypeValidator.Is(bytes);
// Async form
using var asyncStream = File.OpenRead("document.pdf");
bool isPdfAsync = await FileTypeValidator.IsAsync(asyncStream);
```
```
--------------------------------
### Check if File is an Image with FileTypeValidator.IsImage
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Use `FileTypeValidator.IsImage` to determine if a file is any supported image format. Available as static and extension methods for streams, byte arrays, and spans, including async variants.
```csharp
using FileTypeChecker;
using FileTypeChecker.Extensions;
using var stream = File.OpenRead("profile.png");
// Static method
bool isImageStatic = FileTypeValidator.IsImage(stream);
// Extension method on Stream
bool isImageExt = stream.IsImage();
Console.WriteLine($"Is Image: {isImageExt}"); // Is Image: True
// Extension method on byte[]
byte[] bytes = File.ReadAllBytes("profile.png");
bool isImageBytes = bytes.IsImage();
// Extension method on ReadOnlySpan
bool isImageSpan = bytes.AsSpan().IsImage();
// Async
using var asyncStream = File.OpenRead("profile.png");
bool isImageAsync = await FileTypeValidator.IsImageAsync(asyncStream);
```
--------------------------------
### FileTypeValidator.IsTypeRecognizable
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Checks if the binary content of a given input (Stream, byte[], ReadOnlySpan) matches any known file type signature. Returns true if a match is found, false otherwise. An asynchronous version is also available.
```APIDOC
## IsTypeRecognizable
### Description
Determines whether the binary content of the provided input matches any known file type signature. Returns `true` if a match is found, `false` otherwise.
### Method
`FileTypeValidator.IsTypeRecognizable(Stream input)`
`FileTypeValidator.IsTypeRecognizable(byte[] input)`
`FileTypeValidator.IsTypeRecognizable(ReadOnlySpan input)`
`await FileTypeValidator.IsTypeRecognizableAsync(Stream input)`
### Parameters
#### Input
- **input** (Stream | byte[] | ReadOnlySpan) - Required - The binary data to check.
### Request Example
```csharp
// From a file stream
using var fileStream = File.OpenRead("upload.bin");
bool recognized = FileTypeValidator.IsTypeRecognizable(fileStream);
// From a byte array
byte[] fileBytes = File.ReadAllBytes("upload.bin");
bool recognizedFromBytes = FileTypeValidator.IsTypeRecognizable(fileBytes);
// From a ReadOnlySpan
ReadOnlySpan span = fileBytes.AsSpan();
bool recognizedFromSpan = FileTypeValidator.IsTypeRecognizable(span);
// Async version
using var asyncStream = File.OpenRead("upload.bin");
bool recognizedAsync = await FileTypeValidator.IsTypeRecognizableAsync(asyncStream);
```
### Response
- **recognized** (bool) - `true` if the file type is recognizable, `false` otherwise.
### Error Handling
- Throws `ArgumentNullException` if the input is null or empty.
```
--------------------------------
### FileTypeValidator.IsDocument / IsExecutable
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Checks if a file is a document (PDF, Office, XML) or an executable (EXE, ELF). Available as static and extension methods for Stream, byte[], and ReadOnlySpan, including async variants.
```APIDOC
## `FileTypeValidator.IsDocument` / `IsExecutable` — Additional category checks
`IsDocument` detects PDF, Microsoft Office (DOC/DOCX/XLS/XLSX), and XML files. `IsExecutable` detects Windows PE executables (EXE) and ELF binaries. Both are available as static methods and extension methods on `Stream`, `byte[]`, and `ReadOnlySpan`.
### Usage
```csharp
using FileTypeChecker;
using FileTypeChecker.Extensions;
// Document check
using var docStream = File.OpenRead("report.docx");
bool isDoc = docStream.IsDocument();
Console.WriteLine($"Is Document: {isDoc}"); // Is Document: True
// Executable check — useful for blocking EXE uploads
using var exeStream = File.OpenRead("setup.exe");
bool isExe = exeStream.IsExecutable();
Console.WriteLine($"Is Executable: {isExe}"); // Is Executable: True
// Async variants
bool isDocAsync = await FileTypeValidator.IsDocumentAsync(docStream);
bool isExeAsync = await FileTypeValidator.IsExecutableAsync(exeStream);
// Block executables in a file upload handler
public IActionResult Upload(IFormFile file)
{
using var stream = file.OpenReadStream();
if (stream.IsExecutable())
return BadRequest("Executable files are not allowed.");
// proceed with safe upload
}
```
```
--------------------------------
### FileTypeValidator.GetFileType
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Retrieves detailed information about the matched file type, including its name, extension, and MIME type. This method throws a `TypeNotFoundException` if no match is found. Overloads are available for Stream, byte[], ReadOnlySpan, and asynchronous operations.
```APIDOC
## GetFileType
### Description
Returns an `IFileType` instance describing the matched file type, including `Name`, `Extension`, and `MimeType`. Throws `TypeNotFoundException` if no match is found.
### Method
`FileTypeValidator.GetFileType(Stream input)`
`FileTypeValidator.GetFileType(byte[] input)`
`FileTypeValidator.GetFileType(ReadOnlySpan input)`
`await FileTypeValidator.GetFileTypeAsync(Stream input)`
### Parameters
#### Input
- **input** (Stream | byte[] | ReadOnlySpan) - Required - The binary data to analyze.
### Request Example
```csharp
using var fileStream = File.OpenRead("photo.jpg");
IFileType fileType = FileTypeValidator.GetFileType(fileStream);
Console.WriteLine($"Name: {fileType.Name}");
byte[] bytes = File.ReadAllBytes("photo.jpg");
IFileType typeFromBytes = FileTypeValidator.GetFileType(bytes);
IFileType typeFromSpan = FileTypeValidator.GetFileType(bytes.AsSpan());
using var asyncStream = File.OpenRead("photo.jpg");
IFileType asyncType = await FileTypeValidator.GetFileTypeAsync(asyncStream);
```
### Response
- **IFileType** - An object containing file type details:
- **Name** (string) - The full name of the file type (e.g., "Joint Photographic Experts Group").
- **Extension** (string) - The common file extension (e.g., "jpg").
- **MimeType** (string) - The MIME type of the file (e.g., "image/jpeg").
### Error Handling
- Throws `TypeNotFoundException` if no file type match is found.
```
--------------------------------
### FileTypeValidator.IsImage
Source: https://context7.com/ajmitev/filetypechecker/llms.txt
Checks if the file is any supported image format. Available as static and extension methods for Stream, byte[], and ReadOnlySpan, including an async variant.
```APIDOC
## `FileTypeValidator.IsImage` — Category check for images
Returns `true` if the file is any supported image format: BMP, JPEG, GIF (87a/89a), PNG, TIFF, WebP, or ICO. Available as a static method and as an extension method on `Stream`, `byte[]`, and `ReadOnlySpan`.
### Usage
```csharp
using FileTypeChecker;
using FileTypeChecker.Extensions;
using var stream = File.OpenRead("profile.png");
// Static method
bool isImageStatic = FileTypeValidator.IsImage(stream);
// Extension method on Stream
bool isImageExt = stream.IsImage();
Console.WriteLine($"Is Image: {isImageExt}"); // Is Image: True
// Extension method on byte[]
byte[] bytes = File.ReadAllBytes("profile.png");
bool isImageBytes = bytes.IsImage();
// Extension method on ReadOnlySpan
bool isImageSpan = bytes.AsSpan().IsImage();
// Async
using var asyncStream = File.OpenRead("profile.png");
bool isImageAsync = await FileTypeValidator.IsImageAsync(asyncStream);
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.