C# – How to detect antivirus on Windows Server 2008 in C#

antiviruscwindows-server-2008windows-server-2008-r2

I have seen code samples similar to the following numerous times in my search for an answer:

using System;
using System.Text;
using System.Management;

namespace ConsoleApplication1
{
  class Program
  {
    public static bool AntivirusInstalled()
    {

      string wmipathstr = @"\\" + Environment.MachineName + @"\root\SecurityCenter";
      try
      {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmipathstr, "SELECT * FROM AntivirusProduct");
        ManagementObjectCollection instances = searcher.Get();
        return instances.Count > 0;
      }

      catch (Exception e)
      {
        Console.WriteLine(e.Message);
      }

      return false;
    } 

    public static void Main(string[] args)
    {
      bool returnCode = AntivirusInstalled();
      Console.WriteLine("Antivirus Installed " + returnCode.ToString());
      Console.WriteLine();
      Console.Read();
    }

  }
}

Unfortunately, it appears that Windows Server 2008 does not have the SecurityCenter or SecurityCenter2 namespace, so I get an Invalid namespace exception when trying this approach.

Does anyone know of a way to determine if there is antivirus software running on Windows Server 2008? Any help is appreciated!

Best Answer

Use the EICAR test virus.

  1. Have your application try to write one of these files on disk: http://www.eicar.org/85-0-Download.html
  2. Catch the exception

It will not only work on every anti-virus on earth, but it will also tell you if the anti-virus is active!

You may find it hard to download the test file if you have anti-virus active, so you may want to use this string instead:

X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*

Keep in mind, you probably want to keep the string encoded on your app and decode it just before you write it to disk. Otherwise you may risk your app being detected as a virus :)

On the EICAR site, they say:

Any anti-virus product that supports the EICAR test file should detect it in any file providing that the file starts with the following 68 characters, and is exactly 68 bytes long

However, I wouldn't count AV developers have read the spec, so better just keep the string encoded. In fact, I just tried to save the string on a .txt file on my desktop with some additional characters in it and Windows Defender started screaming.