简体   繁体   中英

C# Getting a list of names of the webcams

I have searched for several days to no avail. I am trying to simply list to a text file the Image Device Names ie webcams using c#. I know I can use System.IO.Ports to get comports, which I am doing, but I cannot find a simple way to list the Image Devices.

I have been able to find the WIA devices with this code but not non-WIA Devices:

    private static void DoWork()
    {
        var deviceManager1 = new DeviceManager();
        for (int i = 1; (i <= deviceManager1.DeviceInfos.Count); i++)
        {
           // if (deviceManager1.DeviceInfos[i].Type !=   
     WiaDeviceType.VideoDeviceType) { continue; }


     Console.WriteLine(deviceManager1.DeviceInfos[i].
     Properties["Name"].get_Value().  ToString());
     }

As I answered in this question , you can do it without external libraries by using WMI.

Add using System.Management; and then:

public static List<string> GetAllConnectedCameras()
{
    var cameraNames = new List<string>();
    using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')"))
    {
        foreach (var device in searcher.Get())
        {
            cameraNames.Add(device["Caption"].ToString());
        }
    }

    return cameraNames;
}

I have a couple routes for you to check out.

Try adding a reference to Interop.WIA.dll (Microsoft Windows Image Acquisition Library) and using the following code to enumerate the devices. You can then filter for the relevant ones using a device property.

using System;
using WIA;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        DoWork();
        Console.ReadKey();
    }

    private static void DoWork()
    {
        var deviceManager1 = new DeviceManager();
        for (int i = 1; (i <= deviceManager1.DeviceInfos.Count); i++)
        {
            if (deviceManager1.DeviceInfos[i].Type == WiaDeviceType.CameraDeviceType|| deviceManager1.DeviceInfos[i].Type == WiaDeviceType.VideoDeviceType)
            {
                Console.WriteLine(deviceManager1.DeviceInfos[i].Properties["Name"].get_Value().ToString());
            }
        }
    }
}

}

If that doesn't work, you can always try using DEVCON, which is a Microsoft tool. DEVCON allows device management from the command line. You could try invoking it with the appropriate flags and reading the output. ( http://www.robvanderwoude.com/devcon.php )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM