-
Notifications
You must be signed in to change notification settings - Fork 1
Getting Started
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.FileValidatorBrowse the ByteGuard tag on NuGet for available extensions and antimalware scanners.
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 theIsValidFile()functions for comprehensive validation.
IsValidFile()performs, in order:
- Extension validation
- File size validation
- Signature (magic-number) validation
- Optional Open XML / Open Document Format specification conformance validation (for supported types)
- 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");
}
// ...