Search code examples
c#servicecomopccomexception

C# COMException as Windows Service, but WinForms OK


I'm attempting to write a Windows service in C# (VS2010,.NET 4.0) that acts as a long-running OPC client. Depending on the command-line arguments, it can run as a Windows service, or as a WinForms app with a Start/Stop button to emulate a service (but easier to debug).

I'm currently using Interop.OPCAutomation to make the calls to COM. When I run as a WinForms app, everything runs as expected, no errors. But when I run as a Windows service, it fails with the following exception:

[System.Runtime.InteropServices.COMException: "No such interface supported" ErrorCode: -2147220990 at OPCAutomation.IOPCAutoServer.Connect(String ProgID, Object Node) at Project.Opc.Collector..ctor(String serverName, IEnumerable`1 tagNames, String machineName, Boolean asynchronous) in C:\CompanyName\Projects\Applications\Project\Project.Opc\Collector1.cs:line 41

Here is the offending code:

_server = new OPCServer(); //this works OK

try {
    _server.Connect(serverName, machineName); // this is where it fails
} catch (Exception exc) {
    string message = string.Format("Unable to connect to OPC server {0} on {1}", serverName, machineName);
    OpcException exception = new OpcException(message, exc);
    Logger.Log(message, LogLevel.Exception, exception);
    throw exception;
}

I'm running the Windows server version as SYSTEM, and it doesn't work with Allow access to desktop on or off. Since this code works fine in WinForms, it's probably not an OPC problem. But I have no clue why the same code won't work as a service.

A related article has a similar problem, but it remains unanswered. Has anyone else seen and/or solved this issue?


Solution

  • It seems the service account used in the service has no required access for the COM component, to resolve this use the Administrator account or the account used for WinForm (current user).

    Check the this link which is similar to your question.