Skip to content

Getting Started

Christian Haase edited this page Dec 2, 2025 · 2 revisions

Installing from NuGet

ByteGuard FieValidator consists of multiple separate packages, but the core package that does the actual validation is ByteGuard.FileValidator. This package supports .NET Framework 4.8.1+ and .NET Core 5.0+.

dotnet add package ByteGuard.FileValidator

Browse the ByteGuard tag on NuGet for available extensions and antimalware scanners.

Setup & basic usage

All types and classes can be found in the namespace ByteGuard.FileValidator

using ByteGuard.FileValidator;

The file validator is created by instantiating a configuration instance to provide as argument for the file validator itself.

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

var validator = new FileValidator(configuration);

With the file validator you can choose to either validate a single aspect of any given file, or validate considering all parameters and configuration.

// Single validation aspect
var isValidFileType = fileValidator.IsValidFileType(fileName);
var isValidFileSize = fileValidator.HasValidSize(fileStream);
var isSignatureValid = fileValidator.HasValidSignature(fileName, fileStream);
var isOpenXmlValid = fileValidator.IsValidOpenXmlDocument(fileName, fileStream);
var isOpenDocumentFormatValid = fileValidator.IsValidOpenDocumentFormat(fileName, fileStream);
var isMalwareClean = fileValidator.IsMalwareClean(fileName, fileStream);

// Complete validation
var isValid = fileValidator.IsValidFile(fileName, fileStream);

⚠️ It’s recommended to use any of the IsValidFile() functions 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 specification conformance validation (for supported types)
  5. Optional antimalware scanning with a compatible scanning package

If your configuration is set to throw exception when an invalid file is encountered, you can handle the appropriate exceptions through a try-catch.

try
{
    var isValid = fileValidator.IsValidFile(fileName, fileStream);
}
catch(EmptyFileException e)
{
    logger.LogError(e, "File is empty");
}
catch(UnsupportedFileException e)
{
    logger.LogError(e, "File type is not supported");
}
// ...

Clone this wiki locally