How can I find whether a file is infected by virus using VirusTotal.NET library in C#?

Viewed 1226

I am currently using VirusTotal.NET nuget package in my C# MVC project to scan uploaded files. I am using the same example given here https://github.com/Genbox/VirusTotal.NET

VirusTotal virusTotal = new VirusTotal("YOUR API KEY HERE");

//Use HTTPS instead of HTTP
virusTotal.UseTLS = true;

//Create the EICAR test virus. See http://www.eicar.org/86-0-Intended-use.html
byte[] eicar = 
Encoding.ASCII.GetBytes(@"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*");

//Check if the file has been scanned before.
FileReport report = await virusTotal.GetFileReportAsync(eicar);

Console.WriteLine("Seen before: " + (report.ResponseCode == FileReportResponseCode.Present ? "Yes" : "No"));

I am loading the byte array of the uploaded file to eicar variable in the above code. According to the given example, it will provide the file is scanned before or not. But what I actually need is whether the file is infected or not. Can anyone suggest me a solution?

1 Answers

Checking out the UrlReport class, the report you get back has a lot more info than just the response code in their code sample. There are 3 fields that look interesting:

/// <summary>
/// How many engines flagged this resource.
/// </summary>
public int Positives { get; set; }

/// <summary>
/// The scan results from each engine.
/// </summary>
public Dictionary<string, UrlScanEngine> Scans { get; set; }

/// <summary>
/// How many engines scanned this resource.
/// </summary>
public int Total { get; set; }

This may give you the results you're looking for. VirusTotal actually returns results for multiple scan engines, some of which might detect a virus and some which might not.

Console.WriteLine($"{report.Positives} out of {report.Total} scan engines detected a virus.");

You could do anything you want with that data, like calculate the percentage:

var result = 100m * report.Positives / report.Total;
Console.WriteLine($"{result}% of scan engines detected a virus.");

Or just treat a majority of positive scan engine results as an overall positive result:

var result = Math.Round(report.Positives / Convert.ToDecimal(report.Total));
Console.WriteLine($"Virus {(result == 0 ? "not detected": "detected")});
Related