Search code examples
c#.netfilestreamantivirusappdata

How can I get Bitdefender (antivirus) to scan a file and delete it if the file contains a virus?


This is the code I use to write my file to the app_data folder:

var filename = Server.MapPath("~/App_Data") + "/" thefilename;
var ms = new MemoryStream();

file.InputStream.CopyTo(ms);
file.InputStream.Position = 0;
byte[] contents = ms.ToArray();

var fileStream = new System.IO.FileStream(filename, System.IO.FileMode.Create,
System.IO.FileAccess.ReadWrite);
fileStream.Write(contents, 0, contents.Length);

fileStream.Close();

This writes the file fine. However, if there is a virus on it, Bitdefender does not delete this file, unless I go on the IIS and manually try to open/move the file. If I do that, then it is instantly deleted.

If I copy and paste the test virus file into the app_data folder directly then Bitdefender removes it instantly.

I have tried to use various ways to read/move the file with System.IO.File.Move/Open/ReadAllLines. Yet, nothing triggers bit defender to remove the file.

The only thing I got to work was creating a new process to open the file. However, I don't want to be doing that on the server. I am looking for a different solution. This is the code that I've used to open the file, which does cause Bitdefender to scan and remove the infected file:

Process cmd = new Process();
cmd.StartInfo.FileName = filename;
cmd.Start();

A solution with System.IO.File.Open would be best for me in this situation, but I cannot figure out why it isn't working. Alternately, a way to trigger Bitdefender to instantly scan the file would also be a viable solution.


Solution

  • I have solved the issue with the help of @sheavens and following code:

    Process cmd = new Process();
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.FileName = @"C:\Program Files\Bitdefender\Endpoint Security\product.console.exe";
    var args = String.Format("/c FileScan.OnDemand.RunScanTask custom path=\"{0}\" infectedAction1=delete", filename);
    startInfo.Arguments = args;
    cmd.StartInfo = startInfo;
    cmd.StartInfo.UseShellExecute = false;
    cmd.StartInfo.RedirectStandardOutput = true;
    cmd.StartInfo.RedirectStandardError = true;
    var result = cmd.Start();
    

    This creates a new process and looks up the bitdefender exe, and then runs a command to scan the file at the provided path.