Search code examples
c#wmiprintersnetwork-printers

How to change a printer's PortName using c#


I've scanned SO and didn't see this question posted, sorry if I missed it and this is a repeat.

I can locate the network printer in the PrinterSettings.InstalledPrinters, and fetch the "PortName" property from printer.Properties, but just setting the property doesn't work. I tried to brute force the change for that printer portname in the registry and that didn't work either (although I really didn't think it would but had to try).

I have the new port implemented through a reg file load so don't need to build a port. (BTW I know the port works because setting it in the printer properties works fine).

Your help appreciated.

Thanks


Solution

  • You could use WMI to set the PortName for your printer. Here is an example:

    ManagementScope scope = new ManagementScope(@"\root\cimv2");
    scope.Connect();
    
    // Insert your printer name in the WHERE clause...
    ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer WHERE Name='PrinterName");
    
    
    foreach (ManagementObject printer in searcher.Get())
    {
      printer["PortName"]="LPT1:";
      printer.Put();  // Important: Call put to save the settings.
    }
    

    Hope, this helps.