Skip to content

ByteGuard-HQ/byteguard-file-validator-net

ByteGuard File Validator NuGet Version

ByteGuard.FileValidator is a lightweight security-focused library for validating user-supplied files in .NET applications.
It helps you enforce consistent file upload rules by checking:

  • Allowed file extensions
  • File size limits
  • File signatures (magic numbers) to detect spoofed types
  • Security validation for Office Open XML / Open Document Formats (.docx, .xlsx, .pptx, .odt, .odp, .ods)
  • Malware scan result using a varity of scanners (requires the addition of a specific ByteGuard.FileValidator scanner package)

⚠️ Important: This package is one layer in a defense-in-depth strategy.
It does not replace endpoint protection, sandboxing, input validation, or other security controls.

Features

  • ✅ Validate files by extension
  • ✅ Validate files by size
  • ✅ Validate files by signature (magic-numbers)
  • ✅ Validate specification conformance for archive-based formats (Open XML and Open Document Formats)
  • Ensure no malware through a variety of antimalware scanners
  • ✅ Validate using file path, Stream, or byte[]
  • ✅ Configure which file types to support
  • ✅ Configure whether to throw exceptions or simply return a boolean
  • Fluent configuration API for easy setup

Getting Started

Installation

This package is published and installed via NuGet.

Reference the package in your project:

dotnet add package ByteGuard.FileValidator

Antimalware scanners

In order to use the antimalware scanning capabilities, ensure you have a ByteGuard.FileValidator antimalware package referenced as well. You can find the relevant scanner package on NuGet under the namespace ByteGuard.FileValidator.Scanner.

Usage

Basic validation

var configuration = new FileValidatorConfiguration
{
  SupportedFileTypes = [FileExtensions.Pdf, FileExtensions.Jpg, FileExtensions.Png],
  FileSizeLimit = ByteSize.MegaBytes(25),
  ThrowExceptionOnInvalidFile = false
};

// Without antimalware scanner
var fileValidator = new FileValidator(configuration);
var isValid = fileValidator.IsValidFile("example.pdf", fileStream);

// With antimalware
var antimalwareScanner = AntimalwareScannerImplementation();
var fileValidator = new FileValidator(configuration, antimalwareScanner);
var isValid = fileValidator.IsValidFile("example.pdf", fileStream);

Using the fluent builder

var configuration = new FileValidatorConfigurationBuilder()
  .AllowFileTypes(FileExtensions.Pdf, FileExtensions.Jpg, FileExtensions.Png)
  .SetFileSizeLimit(ByteSize.MegaBytes(25))
  .SetThrowExceptionOnInvalidFile(false)
  .Build();

var fileValidator = new FileValidator(configuration);
var isValid = fileValidator.IsValidFile("example.pdf", fileStream);

Validating specific aspects

The FileValidator class provides methods to validate specific aspects of a file.

⚠️ It’s recommended to use IsValidFile for comprehensive validation.

IsValidFile performs, in order:

  1. Extension validation
  2. File size validation
  3. Signature (magic-number) validation
  4. Optional Open XML / Open Document Format security validation (for supported types)
  5. Optional antimalware scanning with a compatible scanning package
bool isExtensionValid = fileValidator.IsValidFileType(fileName);
bool isFileSizeValid = fileValidator.HasValidSize(fileStream);
bool isSignatureValid = fileValidator.HasValidSignature(fileName, fileStream);
bool isOpenXmlValid = fileValidator.IsValidOpenXmlDocument(fileName, fileStream);
bool isOpenDocumentFormatValid = fileValidator.IsValidOpenDocumentFormat(fileName, fileStream);
bool isMalwareClean = fileValidator.IsMalwareClean(fileName, fileStream);

Example

[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
    using var stream = file.OpenReadStream();

    var antimalwareScanner = AntimalwareScannerImplementation();

    var configuration = new FileValidatorConfiguration
    {
        SupportedFileTypes = [FileExtensions.Pdf, FileExtensions.Docx],
        FileSizeLimit = ByteSize.MegaBytes(10),
        ThrowExceptionOnInvalidFile = false
    };

    var validator = new FileValidator(configuration, antimalwareScanner);

    if (!validator.IsValidFile(file.FileName, stream))
    {
        return BadRequest("Invalid or unsupported file.");
    }

    // Proceed with processing/saving...

    return Ok();
}

Supported File Extensions

The following file types are supported by the FileValidator:

Category Supported extensions
Documents .doc, .docx, .xls, .xlsx, .pptx, .odp, .ods, .odt, .pdf, .rtf
Images .jpg, .jpeg, .png,, .bmp
Video .mov, .avi, .mp4
Audio .m4a.mp3, .wav

Validation coverage per type

IsValidFile always validates:

  • File extension (against SupportedFileTypes)
  • File size (against FileSizeLimit)
  • File signature (magic number)
  • Malware scan result (if an antimalware scanner has been configured)

For some formats, additional checks are performed:

  • Microsoft Office / Open Document Format (.docx, .xlsx, .pptx, .ods, .odp, .odt):

    • Extension
    • File size
    • Signature
    • Basic specification conformance validation
    • Malware scan result
  • Other binary formats:

    • Extension
    • File size
    • Signature
    • Malware scan result

Configuration Options

The FileValidatorConfiguration supports:

Setting Required Default Description
SupportedFileTypes Yes N/A A list of allowed file extensions (e.g., .pdf, .jpg).
Use the predefined constants in FileExtensions for supported types.
FileSizeLimit Yes N/A Maximum permitted size of files.
Use the static ByteSize class provided with this package, to simplify your limit.
ThrowExceptionOnInvalidFile No true Whether to throw an exception on invalid files or return false.

File type specific validation rules

The FileValidatorConfiguration contains file type specific validation rules through FileTypeRules. These settings allow for fine control over validation rules for the individual file types, where supported.

ODF rules

Setting Default Description
 RequireMimetype true  Whether a mimetype file is required to pass validation

Open XML rules

Setting Default Description
PerformConformanceValidation true  Whether a conformance/specification validation should be performed as part of the seucirt validation
ConformanceVersion  Office2010 Defines the version speification version to validate against (valid options are defined by FileFormatVersion in DocumentFormat.OpenXml)

Exceptions

When ThrowExceptionOnInvalidFile is set to true, validation functions will throw one of the appropriate exceptions defined below. However, when ThrowExceptionOnInvalidFile is set to false, all validation functions will either return true or false.

Exception type Scenario
EmptyFileException Thrown when the file content is null or empty, indicating a file without any content.
UnsupportedFileException Thrown when the file extension is not in the list of supported types.
InvalidFileSizeException Thrown when the file size exceeds the configured file size limit.
InvalidSignatureException Thrown when the file's signature does not match the expected signature for its type.
InvalidOpenXmlFormatException Thrown when the validation of an Open XML file is invalid (.docx, .xlsx, .pptx, etc.).
InvalidOpenDocumentFormatException Thrown when the validation of an Open Document Format file is invalid (.odt, .ods, .odp etc.).
MalwareDetectedException Thrown when the configured antimalware scanner detected malware in the file from a scan result.

When to use this package

  • ✅ Whenever you need consistent file validation rules across projects
  • ✅ When handling user uploads in APIs or web applications
  • ✅ When you want defense-in-depth against spoofed or malicious files

License

ByteGuard FileValidator is Copyright © ByteGuard Contributors - Provided under the MIT license.

About

ByteGuard File Validator is a security-focused .NET library for validating user-supplied files, providing a configurable API to help you enforce safe and consistent file handling across your applications.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Contributors