I have a usb printer. I don't know how to take device id also. I want to take vid/ pid using c# code. Any help appreciated.
Have you tried:
using System.Management;
ManagementObjectSearcher myPrinterObject = new ManagementObjectSearcher("select * from Win32_Printer");
foreach (ManagementObject obj in myPrinterObject.Get())
{
Console.WriteLine("Name - " + obj["Name"]);
Console.WriteLine("Network - " + obj["Network"]);
Console.WriteLine("Availability - " + obj["Availability"]);
Console.WriteLine("Is default printer - " + obj["Default"]);
Console.WriteLine("DeviceID - " + obj["DeviceID"]);
Console.WriteLine("Status - " + obj["Status"]);
Console.WriteLine(String.Empty.PadLeft(obj["Name"].ToString().Length, '='));
}
The WMI properties are:
https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-printer?redirectedfrom=MSDN
You can also wrap the manufacturer DLL with a C++ wrapper and then call that from your C# application seamlessly however this will could take you a long time to write!
Related
Just to clear the wind I am aware off that granting users sysadmin in T-SQL in not a good thing but per customer requirements it needs to be done.
I have this :
public void AddUserToServer(List<string> users, List<string> servers)
{
foreach (var server in servers)
{
setConnection(server);
foreach (var user in users)
{
string sql =
"USE [master]" +
" CREATE LOGIN" + " [TP1\\" + user + "] FROM WINDOWS WITH DEFAULT_DATABASE=[master], " +
"DEFAULT_LANGUAGE=[us_english] " +
"EXEC sys.sp_addsrvrolemember #loginame = N'TP1\\" + user + "', #rolename = N'sysadmin'";
_dbContext.Database.ExecuteSqlCommand(sql);
}
}
}
I got the above script by creating the user manually in ssms and then generated the script. However when running it I am getting this current error:
'The procedure 'sys.sp_addsrvrolemember' cannot be executed within a transaction.
So I changed it to :
string sql =
"USE [master]" +
" CREATE LOGIN" + " [TP1\\" + user + "] FROM WINDOWS WITH DEFAULT_DATABASE=[master], " +
"DEFAULT_LANGUAGE=[us_english] " +
"GRANT ADMINISTER BULK OPERATIONS TO[TP1\\" + user + "]";
This creates the user BUT I do not get the sysadmin role.
How do I solve this?
So typical that I spent some time on this and finally after positing I find the answer.
I believe that this is a question more people will ask so I can provide what I found:
string sql =
"USE [master]" +
" CREATE LOGIN" + " [TP1\\" + user + "] FROM WINDOWS WITH DEFAULT_DATABASE=[master], " +
"DEFAULT_LANGUAGE=[us_english] " +
"EXEC sys.sp_addsrvrolemember #loginame = N'TP1\\" + user + "', #rolename = N'sysadmin'";
_dbContext.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, sql);
NOTE:
TransactionalBehavior.DoNotEnsureTransaction
Starting with EF6 Database.ExecuteSqlCommand() by default will wrap
the command in a transaction if one was not already present. There are
overloads of this method that allow you to override this behavior if
you wish. Also in EF6 execution of stored procedures included in the
model through APIs such as ObjectContext.ExecuteFunction() does the
same (except that the default behavior cannot at the moment be
overridden).
Found the answer here
I'm using the following code to get my drive serial number. It's working fine with Windows 7, 8, 8.1, and 10 Professional, but I'm getting an error on Windows 10 Home.
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject wmi_HD in searcher.Get())
{
if (wmi_HD["SerialNumber"] == null)
hddId = null;
else
hddId = wmi_HD["SerialNumber"].ToString();
}
I'm getting
System.NullReferenceException : Object reference not set to an instance of an object.
Does anyone know why? What do I need to do to get the serial number in this case?
One more question: if I boot the OS from my pendrive, will this code work? How could I know that the OS is running from a pendrive or disk or any other resource?
When I go to the Device Manager, I see this:
I am adding this as an answer because it can save lot of time while debugging scenarios like System.NullReferenceException in WMI.
Windows+R (run command)
Type wbemtest
And connect to the machine for which you want to fetch information. Fire the query for Win32_DiskDrive and check the output for properties that you can fetch.
This is what I'm using on Windows 10 v1809:
using System;
using System.Management;
namespace GetSerialNo
{
class Program
{
static void Main(string[] args)
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject info in searcher.Get())
{
Console.WriteLine("DeviceID: " + info["DeviceID"].ToString());
Console.WriteLine("Model: " + "Model: " + info["Model"].ToString());
Console.WriteLine("Interface: " + "Interface: " + info["InterfaceType"].ToString());
Console.WriteLine("Serial#: " + "Serial#: " + info["SerialNumber"].ToString());
}
Console.ReadLine();
}
}
}
For details please see http://csharphelper.com/blog/2017/10/get-hard-drive-serial-number-c/
For the associated link Get Hard disk serial Number given by #ADreNaLiNe-DJ I wasn't able to find the required assembly reference for HardDrive hd = new HardDrive();
How can I get file attributes or version info of driver file in windows via c#.
I'm using this code:
var version = File.GetAttributes(Environment.SystemDirectory + #"\drivers\acpi.sys");
but this code throw exception: Could not find file 'C:\Windows\system32\drivers\acpi.sys'..
Then i'm using this code var dir = Directory.GetFiles(Environment.SystemDirectory + #"\drivers"); in dir variable i have 4 files. If I open this folder via windows explorer i have in folder 300+ files. What am I doing wrong?
You should using >= FrameWork .net 4,
add :
using System.Management;
and add the reference System.Management;
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PnPSignedDriver");
ManagementObjectCollection moc = searcher.Get();
foreach (var manObj in moc)
{
Console.WriteLine("Device Name:" + manObj["FriendlyName"] + " \r\nDeviceID: " + manObj["DeviceID"] + "\r\nDriverDate: " + manObj["DriverDate"] + "\r\nDriverVersion: " + manObj["DriverVersion"] + "\r\nDriverName:" + manObj["DriverName"] +"\n\r======================================\n\n";);
}
Result (part):
Another way could be reading the version from the file directly. Should work for 64/32bit apps, but I am not sure if you can get to all files.
string directory;
if (Environment.Is64BitOperatingSystem)
directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Sysnative");
else
directory = Environment.GetFolderPath(Environment.SpecialFolder.System);
var info = FileVersionInfo.GetVersionInfo(Path.Combine(directory, "drivers", "acpi.sys"));
You can find more information about Sysnative folders at Folders under C:\Windows\System32\GroupPolicyUsers created with Directory or File System Redirector
I'm using my broadband internet through Wan Miniport (PPPOE) connection and I've Windows 7 as my OS. I would like to disconnect the internet connection through C#. I searched a lot over the internet but I'm not sure which methodology (WMI, WinInet etc) suits my connection.
I will be reconnecting through another software later, hence my requirement is just to disconnect from the internet rather totally disabling it permanently.
Kindly please give some solution & code to implement this.
?
Use WMI:
C#:
var wmiQuery = new SelectQuery("SELECT * FROM Win32_NetworkAdapter " +
"WHERE NetConnectionId != null " +
"AND Manufacturer != 'Microsoft' ");
using (var searcher = new ManagementObjectSearcher(wmiQuery))
{
foreach (ManagementObject item in searcher.Get())
{
if (((String)item["NetConnectionId"]) == "Local Area Connection")
{
using (item)
{
item.InvokeMethod("Disable", null);
}
}
}
}
VB:
Dim wmiQuery = New SelectQuery("SELECT * FROM Win32_NetworkAdapter " & "WHERE NetConnectionId != null " & "AND Manufacturer != 'Microsoft' ")
Using searcher = New ManagementObjectSearcher(wmiQuery)
For Each item As ManagementObject In searcher.[Get]()
If DirectCast(item("NetConnectionId"), [String]) = "Local Area Connection" Then
Using item
item.InvokeMethod("Disable", Nothing)
End Using
End If
Next
End Using
I am unable to write the response of a WMI query to file but I can print it to console.
I rewrote the query to use different WMI methods to pull the data. I changed back to the below method of ease of use.
I changed from mo["PackageName"] to mo["PackageName"].ToString() in case the response was not a writable string.
I googled - I have yet to find a similar issue and I am starting to think it is something obvious in my code that I am just overlooking.
//store log in same directory as exe is ran from
StreamWriter writeFile = new StreamWriter(filepath);
ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT PackageName FROM Win32_Product WHERE PackageName LIKE 'jre%%'");
foreach (ManagementObject mo in mos.Get())
{
if (mo["PackageName"].ToString().Contains("jre"))
{
String packageName = mo["PackageName"].ToString();
writeFile.WriteLine(host + "," + packageName);
}
}
update
see my answer below:
foreach (ManagementObject mo in mos.Get())
{
if (mo["PackageName"].ToString().Contains("jre"))
{
String packageName = mo["PackageName"].ToString();
writeFile.WriteLine(host + "," + packageName);
writeFile.Flush();
}
}
Without knowing what writeFile is or how it's defined, I can only suggest that you use the easier System.IO.File class, like so:
File.AppendAllText(pathToYourFile, host + "," + packageName);
This will automatically open, write to, and close your file for you.
I use the WMI Code Creator for WMI query code creation.
It creates C# code and it is possible to test the queries.
Not a real answer - but might help.
I forgot to flush the writer after write.
String packageName = mo["PackageName"].ToString();
writeFile.WriteLine(host + "," + packageName);
writeFile.Flush();