Printer status return wrong value - c#

I am trying to get the status of a network printer. I tried WMI code as this link says. But even if I removed the network cable, it always goes to the else part.
Here is the code I tried :
ManagementObjectSearcher searcher = new
ManagementObjectSearcher("SELECT * FROM Win32_Printer");
string printerName = "";
foreach (ManagementObject printer in searcher.Get())
{
printerName = printer["Name"].ToString().ToLower();
if (printer["WorkOffline"].ToString().ToLower().Equals("true") && printer["Default"].ToString().ToLower().Equals("true"))
{
string s = "Printer offline" + printerName;
listBox1.Items.Add(s);
}
else
{
// printer is not offline
// Console.WriteLine("Your Plug-N-Play printer is connected.");
string s = "Printer found and is online " + printerName;
listBox1.Items.Add(s);
}

Check out the condition
printer["PrinterState"].ToString().ToLower().Equals("Offline")
// this would mean offline == Offline which would be false
you would need the comparison in lower case, you have a typo Offline has a Caps Lock O

the comparison could be not right... 'cause the statement
ConsoleWriteLine(printer["PrinterState"].ToString());
returns "0" when the printer is on line, and "128" when this fault due any reason (power off, uninstalled, cable conection, network troubles, etc)
the right comparisons must be:
printer["PrinterState"].ToString().ToLower().Equals("128") for off line
printer["PrinterState"].ToString().ToLower().Equals("0") for on line

Related

C# WMI SetMTU System.ManagementException

We are working on a programm to configure some NICs.
We have to change IP Adresses, Subnetmask and the MTU.
Everything went well except the MTU Statement:
public void SetMTU()
{
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (networkadapterID == (String)objMO["SettingID"])
{
ManagementBaseObject setMTU;
ManagementBaseObject newMTU = objMO.GetMethodParameters("SetMTU");
Int32 test = 9216;
newMTU["MTU"] = test;
setMTU = objMO.InvokeMethod("SetMTU", newMTU, null);
}
}
}
The correct NIC ID is given. Other WMI Operations succeed but we stuck on that one with error Message:
System.Management.ManagementException: "Die Methode ist ungültig. "
(System.Management.ManagementException: "The Method is invalid.")
We have also tried to use "test" as string or uint32 (because the microsoft docs says it's an uint32),also:
newMTU["MTU"] = new (u)int[] { MTU };
but it doesnt work either.
Meanwhile we don't have any ideas how to fix the problem.
I am grateful for every idea.
Thanks for your help and have a good day,
Alex
Edit:
Code to read the MTU should be (you have to tell this part a NetworkID so you don't read the Value of every NIC, you find this in your registry, but you should be able to delete the if part):
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if (networkadapterID == (String)objMO["SettingID"])
{
MessageBox.Show(Convert.ToString(objMO["MTU"]) + ": " + Convert.ToString(objMO["SettingID"]));
}
}
So far we didn't get the problem solved but we now check if the OS is Windows 10 and we will start a PowerShell task with this command:
Get-NetAdapterAdvancedProperty -Name 'NICName' -DisplayName 'Jumbo-Rahmen' | Set-NetAdapterAdvancedProperty -RegistryValue 'MTUsize';
Jumbo-Rahmen should be JumboPacket on an English OS
If the OS is not Windows 10 the User will be asked to change the MTU manually

Unable to format a drive using ManagementObject from Non-Admin account

I have below code to format a USB drive. Code works fine with Admin account, but if I run the exe using Non Admin account, it returns 3 (Access Denied).
I want to format a drive in Non-Admin mode. Any help?
I visited this link https://social.msdn.microsoft.com/Forums/en-US/1e192745-9d58-4507-93f0-ceacbc0cde96/wmi-win32volume-format-method-returns-access-denied?forum=windowsgeneraldevelopmentissues , but no help
ManagementObjectSearcher searcher = new ManagementObjectSearcher(#"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");
foreach (ManagementObject vi in searcher.Get())
{
var result = vi.InvokeMethod("Format", new object[] { fileSystem, quickFormat, clusterSize, label, enableCompression });
if (Convert.ToInt32(result) != 0)
{
throw new Exception("Error while formating drive");
}
}
Have you tried "Right Click> Compatibility> Change All User Settings> Run As Administrator"?
If this is the solution, you can do this with the code.
Probably, this question - answer, can answer your problem.
How do I force my .NET application to run as administrator?

C# Update Network Adapter Name partially working (WinReg good, ipconfig bad)

Given the following function:
private void UpdateNetworkAdapterName(string pnpDevID, string oldAdpterName, string newAdapterName)
{
string guid = "";
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection queryCollection = searcher.Get();
foreach (ManagementObject m in queryCollection)
{
if (string.Equals(m["PNPDeviceID"].ToString(), pnpDevID))
{
guid = m["GUID"].ToString();
break;
}
}
RegistryKey regKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, Environment.MachineName, RegistryView.Registry64);
regKey = regKey.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + guid + "\\Connection", true);
regKey.SetValue("Name", newAdapterName);
bool successful = false;
foreach (NetworkInterface netAd in NetworkInterface.GetAllNetworkInterfaces())
{
if (netAd.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
if (string.Equals(netAd.Name, newAdapterName))
{
Console.WriteLine($"Successfully updated network adapter from {oldAdpterName} to {newAdapterName}");
successful = true;
break;
}
}
}
if (!successful)
{
Console.WriteLine($"Failed to updated network adapter from {oldAdpterName} to {newAdapterName}");
}
}
This successfully updated the correct adapter 'Name' data within Windows Registry and the correct adapter name in the Network and Sharing Centre.
However, I get the failed message internally from the code (no exceptions thrown though (have removed exception handling code for readability)) and doing an ipconfig shows that the adpater name has not been updated.
Environment is Windows10 (needs to also work on Windows7), both 64bit architectures, application built as a 32bit application.
Any ideas what is going on? I am at a total loss at this point.
Thanks in advance.
Just realised that I have all the information to just do a netsh command:
netsh interface set interface name="" newname=""

To get provider from ManagementObjectSearcher Win32_PnPEntity

I am searching for my USB to Serial converter. I have two objectives:
To get the USB Port Number
To get the Provider
Here under is the screenshot from my Device Manager
Now my motto is to recognize this USB to Serial Bridge which is provided by ATEN, However I am not specifically looking for the ATEN thing, just I need to know how to query ManagementObject
Because if I look for Caption for some systems it is ATEN USB to Serial Bridge and for some systems it is USB-to-Serial Comm. Port, and maybe for some other it will become something else. What never changes is the Provider - "ATEN"
Following is my code:
Now I have did something here under to get/extract data from **CAPTION**
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE Caption like '%ATEN USB to Serial Bridge%'"))
{
foreach (ManagementObject queryObj in searcher.Get())
{
foreach (PropertyData prop in queryObj.Properties)
{
listBox1.Items.Add(String.Format("{0}: {1}", prop.Name, prop.Value));
}
string s = queryObj["Caption"].ToString();
// Here under i play with the string `s` to get the `CCOM21`
int start = s.IndexOf("(");
int end = s.IndexOf(")");
result = s.Substring(start, end - start);
result = result.Replace("(", "");
list.Items.Add(result);
}
}
I know its not the right way to do but how I can get the COM21 port and Provider - ATEN by query ManagementObject. Or is there any other direct way to do this.

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.
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);
oManagementScope.Connect();
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)
return;
foreach (ManagementObject oItem in oObjectCollection)
{
int state = (int)oItem.InvokeMethod("RenamePrinter", new object[] { newName });
switch (state)
{
case 0:
//Success do noting else
return;
case 1:
throw new AccessViolationException("Access Denied");
case 1801:
throw new ArgumentException("Invalid Printer Name");
default:
break;
}
}
}
Still works great in 2022, thank you. Just had to change type
int
to
UInt32
to avoid new Exception:
UInt32 state = (UInt32)oItem.InvokeMethod("RenamePrinter", new object[] { newName });
switch (state)
{...

Categories