USB Drive Removal Code in C# - c#

When I use this function in c#, it is able to get drive letter but, when I remove the USB stick and test this function, it doesnt go to the Exception.
So could someone help me with where I am going wrong in the function code?
public void GetDriveLetter()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive where InterfaceType='USB'");
foreach (ManagementObject queryObj in searcher.Get())
{
foreach (ManagementObject b in queryObj.GetRelated("Win32_DiskPartition"))
{
foreach (ManagementBaseObject c in b.GetRelated("Win32_LogicalDisk"))
{
// writer.WriteLine("{0}" + "\\", c["Name"].ToString()); // here it will print drive letter
usbDriveLetter = String.Format("{0}" + "\\", c["Name"].ToString());
}
}
}
}
catch (ManagementException e)
{
MessageBox.Show(e.StackTrace);
}
//CombinedPath = System.IO.Path.Combine(usbDriveLetter.Trim(), path2.Trim());
}

You Method wont throw an Exception as nothing is breaking. If you want to throw and Exception when no usb's are found then you can do this.
if (searcher.Get().Count == 0)
throw new ApplicationException("No Usb drives connected");
Update: will return true if any USB device is found
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive where InterfaceType='USB'");
return (from ManagementObject queryObj in searcher.Get()
from ManagementObject b in queryObj.GetRelated("Win32_DiskPartition")
select b).Select(b => b.GetRelated("Win32_LogicalDisk").Count > 0).FirstOrDefault();

Probably it does not go to the exception because as you have removed the USB stick, the device is not even listed and no exception happens.
Why do you want to generate an exception at all in case the usb stick is not plugged in?
also, you could eventually have better luck replacing the specific exception in the catch definition with a simple Exception object but I don't think this is the issue, as I said above probably no exception is thrown simply because you don^t list anymore the removed device.

Related

C# how to effectively detect which graphic card is used [duplicate]

My C# application sits on the embedded box which has Intel motherboard and graphics chipset. ATI graphics card is put on to PCI express. Generally graphics card drives the video, but if ATI card fails then the video comes out from graphics chipset.
I have to detect the failure of ATI graphics card for diagnostic purposes.
Any ideas/sample code on how to do this.
Thanks in advance
Raju
This should hopefully get you started.
Add a reference to System.Management, then you can do this:
ManagementObjectSearcher searcher
= new ManagementObjectSearcher("SELECT * FROM Win32_DisplayConfiguration");
string graphicsCard = string.Empty;
foreach (ManagementObject mo in searcher.Get())
{
foreach (PropertyData property in mo.Properties)
{
if (property.Name == "Description")
{
graphicsCard = property.Value.ToString();
}
}
}
In my case, graphicsCard is equal to
NVIDIA GeForce 8400 GS (Microsoft
Corporation - WDDM v1.1)
I'm not a fan of how the selected answer only returns the first video controller. Also, there's no need to loop over all the properties. Just get the ones you need. If CurrentBitsPerPixel is not null, then you're looking at one of the active controllers. I'm using Win32_VideoController as suggested by #bairog, instead of the deprecated Win32_DisplayConfiguration.
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
foreach (ManagementObject mo in searcher.Get())
{
PropertyData currentBitsPerPixel = mo.Properties["CurrentBitsPerPixel"];
PropertyData description = mo.Properties["Description"];
if (currentBitsPerPixel != null && description != null)
{
if (currentBitsPerPixel.Value != null)
System.Console.WriteLine(description.Value);
}
}
My machine has 3 video controllers. The first one is not active (ShoreTel). The second one is active, but is not the video card (Desktop Authority). The third one is my NVidia. This code will print out both the DA controller and the NVidia controller.
Promoted answer works only for single video card system. When I have ATI and Nvidia cards - WMI query returns ATI even if that monitor is plugged into Nvidia card, dxdiag shows Nvidia and games runs on that card (usage).
The only way I could determine right video card was using SlimDX to create DX device and examine what card it used. However that .dll weights over 3Mb.
var graphicsCardName = new Direct3D().Adapters[0].Details.Description;
Your question isn't entirely clear, so I'm not sure if the follwing idea will help or not.
Perhaps something very simple would suffice:
If the two graphics cards run different resolutions check the monitor resolution using:
System.Windows.Forms.SystemInformation.PrimaryMonitorSize
Similarly, if one card supports more than one monitor, check the number of monitors using SystemInformation.MonitorCount.
I tried all the approaches in this question but none gives me a correct answer. However I found it possible to get your current using the Win32_DisplayControllerConfiguration class. Although according to MSDN this class is obsolete, it's the only one returning a correct answer:
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_DisplayControllerConfiguration");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("----------------------------------- ");
Console.WriteLine("Win32_DisplayControllerConfiguration instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Name: {0}", queryObj["Name"]);
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
}
}
(Code generated by WMI Code Creator, a great tool if you are messing with WMI.)
This gives GeForce GTX 1080 on my Windows 10 (RS2) + Intel(R) HD Graphics 4600 + NVIDIA GeForce GTX 1080 system.
Sometimes I need to switch between the Nvidia GPU and onboard GPU. To know which is connected to the monitor, I use the property MinRefreshRate. It works reliably for me, not CurrentBitsPerPixel.
public static void UpdateActiveGpu()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
foreach (ManagementObject mo in searcher.Get())
{
PropertyData minRefreshRate = mo.Properties["MinRefreshRate"];
PropertyData description = mo.Properties["Description"];
if (minRefreshRate != null && description != null && minRefreshRate.Value != null)
{
Global.Instance.activeGpu = description.Value.ToString();
break;
}
}
}

Use of Dismount method of the Win32_Volume

How can I dismount a logical drive temporarily on my computer in c#? I am looking for a code that gives me similar results
Dismount/Hide Drives
//Do some work
Mount / Show Drives
I had tried this code to renaming the drive letters, but cannot understand how to use the Dismount method
ManagementObjectSearcher searchDrives = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Volume WHERE label = 'Data'");
foreach (ManagementObject Drive in searchDrives.Get())
{
Drive.Get();
Drive["DriveLetter"] = "M:";
Drive.Put();
}
This is the Method provided by WMI
https://learn.microsoft.com/en-us/previous-versions/windows/desktop/vdswmi/dismount-method-in-class-win32-volume
How should I use it, please?

How can I find out if my microphone is muted

As the title says I'd like to check if my microphone is muted. Or even better get an event if it gets muted/unmuted.
I tried to get some information form the internet. Turns out I simply don't get it. I found out about the "new" Audio Core API which gave me some ideas, sadly I did not find any c# code so I cant figure out how to use any of this.
With the following code I could get some information for my microphone, however nothing changes if I mute it.
ManagementObjectSearcher objSearcher = new ManagementObjectSearcher(
"SELECT * FROM Win32_SoundDevice");
ManagementObjectCollection objCollection = objSearcher.Get();
ManagementObject rodeMic = null;
foreach (ManagementObject obj in objCollection)
{
foreach (PropertyData property in obj.Properties)
{
if (property.Name == "DeviceID" && (string) property.Value == "USB\\VID_...")
{
rodeMic = obj;
}
}
}
if (rodeMic != null)
{
foreach (var property in rodeMic.Properties)
{
Console.Out.WriteLine(String.Format("{0}:{1}", property.Name, property.Value));
}
}

C# PrintDocument and Printer Status

I am trying to get the printer status of a PointOfSale printer using the following code:
Hashtable properties = new Hashtable();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win2_Printer");
foreach (ManagementObject obj in searcher.Get()) {
if (obj["name"].ToString() == printerName) {
foreach (PropertyData data in obj.Properties) {
if(data.Name.ToLower() = "printerstatus") {
int printerStatus = Convert.ToInt32(data.Value);
}
}
}
}
Problem is, the status is either 3 (idle) or 4(printing), even when unplugged or the paper is out.
I have read a lot of posts with this same issue, but have not found an answer. Is this correct? How else would I check the status? Any help is appreciated.
What Brand of printer are you using?
Sometimes the Brand will have a specific command you can send to query the status.

WMI ManagementObjectSearcher Invalid Class

Hello I've got a bit of a problem. I'm trying to use WMI to list information about disks. When I run the code from the WMI code creator everything returns fine and I get the information I'm looking for. When I run the code from the application I'm writing I get an invalid class error that gets thrown from the foreach loop.
The code I wrote and WMI generated is essentially the same, only the output is different. What could I possibly be doing wrong. Here is the code I wrote.
public List<diskData> getDiskInfo()
{
List<diskData> dData = new List<diskData>();
diskData mydisk = null;
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM W32_LogicalDisk");
foreach (ManagementObject item in searcher.Get())
{
mydisk.name = Convert.ToString(item["Name"]);
}
return dData;
}
catch (Exception ex)
{
Console.WriteLine("This is the Message: " + ex.Message);
return dData;
}
}
Thanks for any help you guys can provide.
Paul
The Win32_LogicalDisk class name in your WMI query is misspelled as W32_LogicalDisk.

Categories

Resources