Renaming Printer using C# and WMI


I have created a C# application to rename printers on a Citrix server (Server 2008 R2).

The reason for this is because every time a user logs on the printer gets forwarded to the server and gets a unique name(For example Microsoft XPS Document Writer (from WI_UFivcBY4-wgoYOdlQ) in session 3) and from within some applications thats an issue since the printer is pointed to the name and by that you need to change the printer setting everytime you logon a session.

The program itself works like a charm and the printer gets the names I desire. However the issue is after that the printers have been renamed Windows does not seem to be able to identify them anymore. For example if I try to change default printer i get an error saying "Error 0x00000709 Double check the printer name and make sure that the printer is connected to the network."

            var query = new ManagementObjectSearcher("SELECT * FROM Win32_Printer where name like '%(%'"); 

            ManagementObjectCollection result = query.Get();

            foreach (ManagementObject printer in result)
                string printerName = printer["name"].ToString();

                if (printerName.IndexOf('(') > 0)
                    printer.InvokeMethod("RenamePrinter", new object[] { printerName.Substring(0, printerName.IndexOf('(')).Trim() + " " + userName }); //userName is provided as an inputparameter when running the application

Am I missing anything? Are there anything else i need to do when renaming? I cant seem to find any info regarding this case at all.

asked on Stack Overflow May 10, 2013 by user2371138

1 Answer


i thing this codeproject is what your looking for. But after some own experiences with the printers in C# i can only say it does not make fun and it can be really frustrating

Code with small modifications:

//Renames the printer
public static void RenamePrinter(string sPrinterName, string newName)
    ManagementScope oManagementScope = new ManagementScope(ManagementPath.DefaultPath);

    SelectQuery oSelectQuery = new SelectQuery();
    oSelectQuery.QueryString = @"SELECT * FROM Win32_Printer WHERE Name = '" + sPrinterName.Replace("\\", "\\\\") + "'";

    ManagementObjectSearcher oObjectSearcher =
        new ManagementObjectSearcher(oManagementScope, oSelectQuery);
    ManagementObjectCollection oObjectCollection = oObjectSearcher.Get();

    if (oObjectCollection.Count == 0)

    foreach (ManagementObject oItem in oObjectCollection)
        int state = (int)oItem.InvokeMethod("RenamePrinter", new object[] { newName });
        switch (state)
            case 0:
                //Success do noting else
            case 1:
                throw new AccessViolationException("Access Denied");
            case 1801:
                throw new ArgumentException("Invalid Printer Name");
answered on Stack Overflow May 10, 2013 by Venson • edited May 10, 2013 by Venson

User contributions licensed under CC BY-SA 3.0