How to distinguish between USB and floppy devices? - c#

I'm trying to recognize drives types by looping around DriveInfo.GetDrives() result.
But for both USB and floppy I get the same DriveType.Removable value.
How can I distinguish between them?

You can use WMI (Windows Management Instrumentation) to get more than just what's in the DriveInfo class. In this case, you can get the interface type, which will be "USB" for USB drives.
Sample code is below. You need to add a reference to System.Management.
using System.Management;
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_DiskDrive");
foreach(ManagementObject queryObj in searcher.Get())
{
foreach(ManagementObject o in queryObj.GetRelated("Win32_DiskPartition"))
{
foreach(ManagementBaseObject b in o.GetRelated("Win32_LogicalDisk"))
{
Debug.WriteLine(" #Name: {0}", b["Name"]);
}
}
// One of: USB, IDE
Debug.WriteLine("Interface: {0}", queryObj["InterfaceType"]);
Debug.WriteLine("--------------------------------------------");
}
}
catch (ManagementException f)
{
Debug.WriteLine(f.StackTrace);
}
For reference, this MSDN page documents the full list of accessible properties (since you don't get autocomplete on this).

The CD Drive And floppy Drive is not ready so you can try this :
foreach (var dr in DriveInfo.GetDrives())
{
if (dr.IsReady == true)
{
Console.WriteLine(string.Format("name : {0} type : {1}", dr, dr.DriveType));
}
}
This is Easy Way to distinguish Between USB and floppy devices

Related

How to find All Graphic Cards? C#

I used this code for finding graphic cards:
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_DisplayConfiguration");
string graphicsCard = "";
foreach (ManagementObject mo in searcher.Get())
{
foreach (PropertyData property in mo.Properties)
{
if (property.Name == "Description")
{
graphicsCard += property.Value.ToString();
}
}
}
but result is: Nvidia Quadro K6000
How to find all Graphic cards?
The very first line of the MSDN page reads:
[The Win32_DisplayConfiguration WMI class is no longer available for use as of Windows Server 2008. Instead, use the properties in the Win32_VideoController, Win32_DesktopMonitor, and CIM_VideoControllerResolution classes.]
So I suggest you start out with Win32_VideoController.

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.

How to detect Cameras attached to my machine using C#

I am able to know the sound devices and USB Devices attached to my PC but not getting any way to find Cameras attached to my machine.
Used below code to get Sound Devices
Console.WriteLine("Win32 SoundDevices\r\n===============================");
ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_SoundDevice");
foreach (ManagementObject soundDevice in searcher.Get())
{
//Console.WriteLine("Device found: {0}\n", soundDevice.ToString());
Console.WriteLine("Device found: {0}\n", soundDevice.GetPropertyValue("ProductName"));
}
Console.WriteLine("Search complete.");
I wrote a solution that worked well for me. This method found two USB cameras and an integrated camera on my laptop.
private static async Task ListAllCamerasAsync()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM win32_PNPEntity WHERE PnPClass='Camera'");
var collection = await Task.Run(() => { return searcher.Get(); });
var cameraIndex = 0;
foreach (ManagementObject cameraDevice in collection)
{
Console.WriteLine($"Camera {cameraIndex}: {cameraDevice["Name"]}");
cameraIndex++;
}
}
This tool will prove helpful:
http://www.microsoft.com/en-us/download/details.aspx?id=8572
I'm fairly certain there's no equivalent string you can send to ManagementObjectSearcher() for webcams specifically. There is the "Win32_USBControllerDevice" which you can then determine if it is a webcam or not.
A better solution altogether is to take advantage of DirectShow.NET

How to get network adapter index?

From code I want to force a Windows machine to use a specific network adapter for all connections to a specific IP address.
I plan to do so by using the ROUTE ADD command line tool, but this requires that I know in advance the network adapters' index number (as it must be given to the ROUTE ADD command).
QUESTION: How can I programmatically retrieve a network adapter's index, given I know its name?
I'm aware that ROUTE PRINT shows me the information I need (the index numbers of all network adapters present), but there must be a way to get that information programmatically too (C#)?
Note, that I don't like parsing the text output from ROUTE PRINT, as the text format may change with different Windows versions.
You can obtain the interface index of your network adapter
by using the .Net NetworkInterface (and related) classes.
Here is a code example:
static void PrintInterfaceIndex(string adapterName)
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
Console.WriteLine("IPv4 interface information for {0}.{1}",
properties.HostName, properties.DomainName);
foreach (NetworkInterface adapter in nics)
{
if (adapter.Supports(NetworkInterfaceComponent.IPv4) == false)
{
continue;
}
if (!adapter.Description.Equals(adapterName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
Console.WriteLine(adapter.Description);
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties();
if (p == null)
{
Console.WriteLine("No information is available for this interface.");
continue;
}
Console.WriteLine(" Index : {0}", p.Index);
}
}
Then just call this function with the name of your network adapter:
PrintInterfaceIndex("your network adapter name");
You can also obtain the InterfaceIndex of your network adapter
by using the Win32_NetworkAdapter WMI class. The Win32_NetworkAdapter class
contains a property called InterfaceIndex.
So, to retrieve the InterfaceIndex for a network adapter with a given
name, use the following code:
ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter WHERE Description='<Your Network Adapter name goes here>'");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
using (ManagementObjectCollection queryCollection = searcher.Get())
{
foreach (ManagementObject mo in queryCollection)
{
Console.WriteLine("InterfaceIndex : {0}, name {1}", mo["InterfaceIndex"], mo["Description"]);
}
}
}
If you do not want to use WMI you could also use the Win32 API function
GetAdaptersInfo in combination with the IP_ADAPTER_INFO struct.
You will find an example here pinvoke.net.
have you looked into using C#'s system.net.networkinformation interface?
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface.getallnetworkinterfaces.aspx
I'm not familiar with ROUTE ADD, but you can theoretically marry up information from one with the other.

C# detect which graphics card drives video

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;
}
}
}

Categories