I tried this C# code to add printer and printer drivers to Windows. It worked on Windows 7 but not on Windows 8. Exception (Generic failure) occurred when the code calls moPrinter.Put()
. Can anyone tell why this error encountered when running Windows 8, and why not Windows 7?
public static bool AddCanonPrinter()
{
bool flag = true;
try
{
String portNumber = "9100";
String printerIP = "157.198.192.42";
String portName = "IP_" + printerIP;
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
ManagementScope mscope = new ManagementScope(ManagementPath.DefaultPath, options);
mscope.Connect();
ManagementPath mpPort = new ManagementPath("Win32_TCPIPPrinterPort");
ManagementClass mcPort = new ManagementClass(mscope, mpPort, new ObjectGetOptions());
ManagementObject moPort = mcPort.CreateInstance();
moPort.Properties["Name"].Value = portName;
moPort.Properties["HostAddress"].Value = printerIP;
moPort.Properties["PortNumber"].Value = portNumber;
moPort.Properties["Protocol"].Value = 1;
moPort.Put();
ManagementPath mpPrinter = new System.Management.ManagementPath("Win32_Printer");
ManagementClass mcPrinter = new ManagementClass(mscope, mpPrinter, new ObjectGetOptions());
ManagementObject moPrinter = mcPrinter.CreateInstance();
moPrinter.Properties["Name"].Value = "Canon";
moPrinter.Properties["DeviceID"].Value = "Canon";
moPrinter.Properties["DriverName"].Value = "Canon iR C2880/C3380";
moPrinter.Properties["PortName"].Value = portName;
moPrinter.Properties["Network"].Value = true;
moPrinter.Properties["Shared"].Value = false;
moPrinter.Put();
}
catch
{
int msgCode = Marshal.GetLastWin32Error();
string msg = GetSystemMessage(msgCode);
flag = false;
}
return flag;
}
Actually after I investigate the problem, I have found that the printer drivers names are different in windows 8. so the same code could be used and work successfully in windows 8.