Friday, October 12, 2012

Integrating ClamAV into your C# applications

During the VP debate, I decided to write some ClamAV bindings for C# that were up to date. The current C# lib for libclamav that is linked on the ClamAV website is from 2005 and no longer useful. Here is a small introduction.

The main objects you will probably work with as a programmer is probably the ClamEngine and ClamResult objects. Since we are interfacing with a library written in C, we must take into account memory leaks. The ClamEngine implements IDisposable and is intended to be used in the context of a using statement. If you are using .NET 1.1 and do not have the using statement available, you will need to call Dispose() explicitly. Here is an example application:
using System;
using clamsharp;

namespace testing
   class MainClass
 public static void Main (string[] args)
  using (ClamEngine e = new ClamEngine())
   foreach (string file in args)
    ClamResult result = e.ScanFile(file); //pretty simple!
    if (result != null && result.ReturnCode == ClamReturnCode.CL_VIRUS)
     Console.WriteLine("Found: " + result.VirusName);
     Console.WriteLine("File Clean!");
  } //engine is disposed of here and the allocated engine freed
One note: If you want it to build on Windows, you will need to change the DllImport's to point to where ever on Windows you need to point to in ClamBindings.

clamd TCP bindings are probably on their way soon, it will be easy enough. The main code is thoroughly documented, but if you still have question after that, feel free to ask on Github.

If you would like to test this without a real virus, I recommend using EICAR.

No comments:

Post a Comment