Validating whether a file is safe before uploading or reading is essential to prevent security risks such as malware, viruses, or malicious code injection. Below are best practices and techniques for validating file safety:
1. Validate File Type (MIME Type and Extension)
Check File Extension
Ensure only allowed extensions (e.g., .jpg, .pdf,
.docx, etc.):
var allowedExtensions = new[] { ".jpg", ".png", ".pdf" };
var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
if (!allowedExtensions.Contains(fileExtension))
{
throw new InvalidOperationException("Invalid file type.");
}
Check MIME Type (Content-Type)
Don't trust file.ContentType from the browser. Instead, inspect the file's content (see below).
2. Inspect File Content (Magic Bytes/Signature)
Use magic numbers to verify the file type:
using (var reader = new BinaryReader(file.OpenReadStream()))
{
var bytes = reader.ReadBytes(4); // Read enough for signature
var signature = BitConverter.ToString(bytes);
// Example for PNG (89-50-4E-47)
if (signature != "89-50-4E-47")
{
throw new InvalidOperationException("File content does not match expected type.");
}
}
Refer to file signature databases like
Gary Kessler's File Signatures Table.
3. Limit File Size
Set a max file size limit (e.g., 5MB):
const long maxSize = 5 * 1024 * 1024;
if (file.Length > maxSize)
{
throw new InvalidOperationException("File is too large.");
}
Also configure server-side limits in settings (e.g., in ASP.NET Core: RequestSizeLimit or
MaxRequestBodySize).
4. Scan for Malware
Use antivirus APIs or malware scanners before accepting the file:
ClamAV (open-source, cross-platform)
Windows Defender (MpCmdRun.exe -Scan)
VirusTotal API (send hash or file for scanning — usage-limited)
Example (with VirusTotal API):
POST https://www.virustotal.com/api/v3/files
Headers: x-apikey: YOUR_API_KEY
Body: (multipart/form-data file upload)
5. Rename Files to Avoid Path Injection
Never trust client filenames. Sanitize and/or replace with GUID:
var safeFileName = Path.GetRandomFileName() + fileExtension;
6. Store Outside Web Root
Never store uploaded files in a public web directory. This prevents accidental execution or download.
Store files in a secured directory like /app_data/uploads.
7. Avoid Inline Execution
Do not allow direct rendering of uploaded files (e.g., don't return HTML/JS from user-uploaded files).
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Validating whether a file is safe before uploading or reading is essential to prevent security risks such as malware, viruses, or malicious code injection. Below are best practices and techniques for validating file safety:
1. Validate File Type (MIME Type and Extension)
Check File Extension
Ensure only allowed extensions (e.g.,
.jpg,.pdf,.docx, etc.):Check MIME Type (Content-Type)
Don't trust
file.ContentTypefrom the browser. Instead, inspect the file's content (see below).2. Inspect File Content (Magic Bytes/Signature)
Use magic numbers to verify the file type:
Refer to file signature databases like Gary Kessler's File Signatures Table.
3. Limit File Size
Set a max file size limit (e.g., 5MB):
Also configure server-side limits in settings (e.g., in ASP.NET Core:
RequestSizeLimitorMaxRequestBodySize).4. Scan for Malware
Use antivirus APIs or malware scanners before accepting the file:
MpCmdRun.exe -Scan)Example (with VirusTotal API):
5. Rename Files to Avoid Path Injection
Never trust client filenames. Sanitize and/or replace with GUID:
6. Store Outside Web Root
Never store uploaded files in a public web directory. This prevents accidental execution or download.
Store files in a secured directory like
/app_data/uploads.7. Avoid Inline Execution
Do not allow direct rendering of uploaded files (e.g., don't return HTML/JS from user-uploaded files).
Set the correct content-disposition headers:
Summary Checklist