How to Scan Uploaded Files for Viruses in ASP.NET

Protect your backend from malicious uploads using antivirus integration

Posted by Hüseyin Sekmenoğlu on April 04, 2022 Backend Development

Allowing users to upload files can open the door to security threats. A malicious file can contain scripts or executables designed to exploit vulnerabilities in your system or the systems of other users. To protect your application and infrastructure you should scan every uploaded file before saving or processing it. In this article you will learn how to integrate antivirus scanning into an ASP.NET file upload workflow.


๐Ÿง  Why Antivirus Scanning Matters

Uploaded files may include:

  • Embedded scripts in documents or images

  • Renamed executables pretending to be images

  • Known malware attachments

Antivirus scanning adds a vital layer of defense that reduces the risk of compromise.


๐Ÿ› ๏ธ ClamAV: A Free and Open Source Scanner

One popular choice is ClamAV, an open source antivirus engine. It can be installed on Linux or Windows servers and used with ASP.NET apps.

There are two main ways to use ClamAV:

  1. Command-line scanner: Run clamscan or clamdscan on a temporary file

  2. ClamAV daemon: Connect via TCP socket for faster scans

In either case you can automate the process with C#.


โš™๏ธ Installing ClamAV

On Windows:
Download the ClamAV binaries and update virus definitions using:

freshclam

On Linux (Ubuntu):

sudo apt update
sudo apt install clamav clamav-daemon
sudo freshclam

Start the ClamAV daemon:

sudo systemctl start clamav-daemon

๐Ÿงช Calling ClamAV from ASP.NET

Here is a simple example using clamscan from C#:

public bool ScanFileWithClamAV(string filePath)
{
    var process = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = "clamscan",
            Arguments = $"--no-summary \"{filePath}\"",
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        }
    };

    process.Start();
    string output = process.StandardOutput.ReadToEnd();
    process.WaitForExit();

    return !output.Contains("Infected files: 1");
}

This method returns false if the file is infected.

Note: Use full paths and proper file access permissions in production.


๐Ÿงพ Full Example in Upload Pipeline

After receiving the uploaded file:

[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
    if (file == null || file.Length == 0) return BadRequest("Empty file");

    var tempFile = Path.GetTempFileName();
    using (var stream = new FileStream(tempFile, FileMode.Create))
    {
        await file.CopyToAsync(stream);
    }

    var isClean = ScanFileWithClamAV(tempFile);
    System.IO.File.Delete(tempFile);

    if (!isClean)
    {
        return BadRequest("The uploaded file contains a virus");
    }

    // Save or process the clean file
    return Ok("File uploaded successfully");
}

You can also log the scan result and notify administrators if needed.


๐Ÿงฐ Using ClamAV via TCP (clamd)

For better performance you can connect to clamd over a network socket using a .NET client like:

  • nClam โ€“ a lightweight C# wrapper

  • Custom TCP client using ClamAV protocol

Example with nClam:

var clam = new ClamClient("localhost", 3310);
var scanResult = await clam.SendAndScanFileAsync(tempFilePath);
if (scanResult.Result == ClamScanResults.VirusDetected)
{
    return BadRequest($"Virus found: {scanResult.InfectedFiles.First().VirusName}");
}

This is more efficient for high-traffic apps.


๐Ÿ”’ Security Best Practices

  • Always scan before saving the file

  • Never execute or open the uploaded file directly

  • Restrict allowed file types

  • Use antivirus tools alongside other filters and validations

You should also run file uploads in a sandboxed environment if possible.


โœ… Conclusion

Adding virus scanning to your ASP.NET upload flow is critical for application security. With tools like ClamAV you can easily detect and reject malicious files before they reach your system or users. Whether you use a command-line scan or a TCP service, your upload process becomes more secure and robust.