How to scan a file for viruses using C# in .NET Framework

Any time you work with user-submitted content, whether in forums, mobile apps, or support, the threat of viruses always looms in the background. A danger to both your company and your other customers, these digital nuisances must be dealt with decisively. Today we will be looking at how to do just that with a minimum of work. Let’s dive in.

First, run this code snippet in Package Manager’s console, which will install the API client that we will be using.

Install-Package Cloudmersive.APIClient.NET.VirusScan -Version 1.2.9

Now we simply feed the questionable file into the ScanFile function.

using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.VirusScan.Api;
using Cloudmersive.APIClient.NET.VirusScan.Client;
using Cloudmersive.APIClient.NET.VirusScan.Model;
namespace Example
{
public class ScanWebsiteExample
using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.VirusScan.Api;
using Cloudmersive.APIClient.NET.VirusScan.Client;
using Cloudmersive.APIClient.NET.VirusScan.Model;
namespace Example
{
public class ScanFileExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");
// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
// Configuration.Default.AddApiKeyPrefix("Apikey", "Bearer");
var apiInstance = new ScanApi();
var inputFile = new System.IO.Stream(); // System.IO.Stream | Input file to perform the operation on.
try
{
// Scan a file for viruses
VirusScanResult result = apiInstance.ScanFile(inputFile);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ScanApi.ScanFile: " + e.Message );
}
}
}
}

And voila! We are done. This function’s speed is proportional to the size of the file, but is generally rather quick. There is a separate function that can scan websites for potential threats as well.

Image for post
Image for post

Written by

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store