Remove printer and driver

I have the following code:

private void btnDeletar_Click(object sender, RoutedEventArgs e)
{
    string nomeImpressora = null;
    if(cmbImpressoras.SelectedIndex != -1)
        nomeImpressora = cmbImpressoras.SelectedItem.ToString();
    else
        MessageBox.Show("Selecione uma Impressora");

    ManagementScope scope = new ManagementScope(ManagementPath.DefaultPath);
    scope.Connect();
    SelectQuery query = new SelectQuery("select * from Win32_Printer");
    ManagementObjectSearcher search = new ManagementObjectSearcher(scope, query);
    ManagementObjectCollection printers = search.Get();

    foreach (ManagementObject printer in printers)
    {
        string printerName = printer["Name"].ToString().ToLower();

        if (printerName.Equals(nomeImpressora.ToLower()))
        {
            try
            {
                DriverImpressora(printer["DriverName"].ToString());
                printer.Delete();

            }
            catch (Exception)
            {
                MessageBox.Show("Impossível remover impressora!");
            }
            break;
        }
    }
}

Now the doubt:

I believe that only the printer is removed, but, the drive does not, if it does not remove the drive, using the Win32_PrinterDriver class is it possible to remove?

Author: Maniero, 2014-11-14

1 answers

You already know the answer to the first question.

The second is possible, you are on the right track, but it is not so simple. I don't know exactly how to do it but it seems that there is an approximate solution of what you want in a question in the SO. It is in VBS but I think that there it is possible to see all the steps necessary to complete the task. Note that it is necessary to delete other components of the system.

Perhaps the most relevant part is in the answer but see the all so as not to do the service in half.

qry = "SELECT * FROM Win32_PrinterDriver"
For Each driver In objWMIService.ExecQuery(qry)
  If driver.Name = "..." Then driver.Delete_
Next

I put on GitHub for future reference .

 2
Author: Maniero, 2020-09-10 19:28:06