TL;DR
This guide shows you how to make file uploads in your C# application safer and prevent malicious files from being uploaded to your server. We’ll cover checking file types, sizes, and names, plus some extra security measures.
1. Validate File Extension
Never trust the filename provided by the user. Attackers can rename a dangerous file to look harmless (e.g., evil.exe renamed to image.jpg). Check the actual file extension, not just what the user says it is.
string allowedExtensions = ".jpg,.jpeg,.png";
string fileName = Path.GetFileName(fileUploadControl.PostedFile.FileName);
string fileExtension = Path.GetExtension(fileName).ToLower();
if (!allowedExtensions.Contains(fileExtension)) {
// Handle invalid extension - show error message, don't proceed.
Console.WriteLine("Invalid file type!");
}
Important: Convert the extension to lowercase for case-insensitive comparison.
2. Limit File Size
Large files can cause denial-of-service attacks or fill up your server’s storage. Set a maximum file size limit.
long maxFileSize = 10 * 1024 * 1024; // 10MB
if (fileUploadControl.PostedFile.ContentLength > maxFileSize) {
// Handle file too large - show error message.
Console.WriteLine("File is too big!");
}
3. Sanitize Filenames
Remove or replace potentially dangerous characters from the filename to prevent path traversal attacks (where an attacker tries to upload a file outside of your intended directory).
string safeFileName = Path.GetFileNameWithoutExtension(fileName).Replace(" ", "_").Replace(".", "") + fileExtension;
This example replaces spaces with underscores and removes periods. You might need to adjust this based on your specific requirements.
4. Store Files in a Secure Location
Don’t store uploaded files directly within your web application’s root directory. Create a dedicated folder outside of the webroot, and give it limited permissions.
- Create a folder like
/uploads(outside of wwwroot). - Ensure the web server user has only write access to this folder.
string uploadPath = Server.MapPath("~/uploads/"); // Get physical path.
string filePath = Path.Combine(uploadPath, safeFileName);
fileUploadControl.PostedFile.SaveAs(filePath);
5. Content Type Validation
Check the ContentType property of the uploaded file. However, be aware that this can be easily spoofed by attackers.
string contentType = fileUploadControl.PostedFile.ContentType.ToLower();
if (contentType != "image/jpeg" && contentType != "image/png") {
// Handle invalid content type.
Console.WriteLine("Invalid Content Type!");
}
Important: Content type validation should be used in conjunction with file extension checking, not as a sole security measure.
6. Anti-Virus Scanning
Consider integrating an anti-virus scanner to scan uploaded files for malware before saving them. There are several libraries and APIs available for this purpose (e.g., ClamAV).
7. Random Filenames
Generate a unique, random filename for each upload. This makes it harder for attackers to predict the file’s location.
string uniqueFileName = Guid.NewGuid().ToString() + fileExtension;
8. cyber security Considerations
- Input Validation is Key: Always validate all user input, including filenames and content types.
- Least Privilege: Run your web application with the minimum necessary permissions.
- Regular Updates: Keep your server software and libraries up to date to patch security vulnerabilities.
- Logging: Log all file upload attempts, including filenames, sizes, and user information for auditing purposes.

