Use WMI into a Windows Service

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gaxy
    New Member
    • Feb 2012
    • 1

    #1

    Use WMI into a Windows Service

    Hi all.
    I'm trying to realise a service that can install a printer queue given an ip address, a queue name and a driver name. The driver is already installed on the workstation.
    The service has to be installed on every workstation.
    The ip address is used to create the TCP/IP port.

    I tried to realise all this in a c# program (.NET Framework 4.0) and it works like a charm. (all items are created, it runs under my own account)

    I post some sample code below (the TCP/IP port creation):

    Code:
     //create port
    ManagementClass portClass = new ManagementClass("Win32_TCPIPPrinterPort");
    ManagementObject portObject = portClass.CreateInstance();
    
    string portName = "IP_" + ip;
    portObject["Name"] = portName;
                                    portObject["HostAddress"] = ip;
    portObject["PortNumber"] = 9100;
    portObject["Protocol"] = 1;
    portObject["SNMPCommunity"] = "public";
    portObject["SNMPEnabled"] = true;
    portObject["SNMPDevIndex"] = 1;
    
    PutOptions options = new PutOptions();
    options.Type = PutType.UpdateOrCreate;
    //put a newly created object to WMI objects set             
    portObject.Put(options);
    Then I tried to put the same code in a Windows service. The service watches a folder and if there is a new file reads it to retrieve information. After reading, it tries to create the TCP port and the queue.

    The service always gives "Access denied" exception on the portObject.Put( options) line (in the code I posted below). I tried to execute it both as LOCAL SYSTEM and my own account, but it is the same.

    I have Windows XP Pro SP3 32bit. Note that on the laptop of a colleague of mine the same service is actually working!

    I tried also to put a fixed user:

    Code:
    ConnectionOptions co = new ConnectionOptions();
    co.Impersonation = ImpersonationLevel.Impersonate;
    co.Authentication = AuthenticationLevel.Packet;
    co.Timeout = new TimeSpan(0, 0, 30);
    co.EnablePrivileges = true;
    co.Username = "myusername";
    co.Password = "mypassword";
    and in this case I have an exception stating: "User credentials cannot be used for local connections".

    I'm going crazy with this... anybody has any idea? any help will be greatly appreciated.

    Best regards.
Working...