Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检测驱动器c中dvd插入的最佳方法#_C#_Wmi_Driveinfo - Fatal编程技术网

C# 检测驱动器c中dvd插入的最佳方法#

C# 检测驱动器c中dvd插入的最佳方法#,c#,wmi,driveinfo,C#,Wmi,Driveinfo,我尝试使用以下代码使用WMI检测磁盘驱动器中的新媒体插入。但是有没有像在后台线程中与DriveInfo.GetDrives一起使用循环这样的托管解决方案?哪种方法是最好的?当我尝试以下代码时,在其他电脑上出现“磁盘不在驱动器中,请插入磁盘”对话框和“中止、重试和继续”按钮?在五月的机器上,它运转良好 private void DriveWatcher() { try { var wqlEventQuery = new WqlEventQuery

我尝试使用以下代码使用WMI检测磁盘驱动器中的新媒体插入。但是有没有像在后台线程中与DriveInfo.GetDrives一起使用循环这样的托管解决方案?哪种方法是最好的?当我尝试以下代码时,在其他电脑上出现“磁盘不在驱动器中,请插入磁盘”对话框和“中止、重试和继续”按钮?在五月的机器上,它运转良好

private void DriveWatcher()
{
    try
    {
        var wqlEventQuery = new WqlEventQuery
            {
                EventClassName = "__InstanceModificationEvent",
                WithinInterval = new TimeSpan(0, 0, 1),
                Condition =
                    @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5"
            };

        var connectionOptions = new ConnectionOptions
            {
                EnablePrivileges = true,
                Authority = null,
                Authentication = AuthenticationLevel.Default
            };

        var managementScope = new ManagementScope("\\root\\CIMV2", connectionOptions);

        ManagementEventWatcher = new ManagementEventWatcher(managementScope, wqlEventQuery);
        ManagementEventWatcher.EventArrived += CdrEventArrived;
        ManagementEventWatcher.Start();
    }
    catch (ManagementException e)
    {
        MessageBox.Show(e.Message, e.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void CdrEventArrived(object sender, EventArrivedEventArgs e)
{
    var wmiDevice = (ManagementBaseObject) e.NewEvent["TargetInstance"];
    if (wmiDevice.Properties["VolumeName"].Value != null)
        GetDrives();
    else
        GetDrives();
}

private void GetDrives()
{
    if (InvokeRequired)
    {
        Invoke(new GetDrivesDelegate(GetDrives));
    }
    else
    {
        toolStripComboBoxDrives.Items.Clear();
        DriveInfo[] drives = DriveInfo.GetDrives();
        _drives = new Dictionary<string, DriveInfo>();
        int selectedIndex = 0;
        foreach (DriveInfo drive in drives)
        {
            if (drive.DriveType.Equals(DriveType.CDRom))
            {
                if (drive.IsReady)
                {
                    string name = string.Format("{0} ({1})", drive.VolumeLabel, drive.Name.Substring(0, 2));
                    int selectedDrive = toolStripComboBoxDrives.Items.Add(name);
                    _drives.Add(name, drive);
                    selectedIndex = selectedDrive;
                }
                else
                {
                    toolStripComboBoxDrives.Items.Add(drive.Name);
                    _drives.Add(drive.Name, drive);
                }
            }
        }
        toolStripComboBoxDrives.SelectedIndex = selectedIndex;
    }
}
private void DriveWatcher()
{
尝试
{
var wqlEventQuery=新的wqlEventQuery
{
EventClassName=“\uu\u InstanceModificationEvent”,
WithinInterval=新的时间跨度(0,0,1),
状况=
@“TargetInstance ISA'Win32_LogicalDisk'和TargetInstance.DriveType=5”
};
var connectionOptions=新的connectionOptions
{
EnablePrivileges=true,
Authority=null,
身份验证=AuthenticationLevel.Default
};
var managementScope=新的管理范围(\\root\\CIMV2”,连接选项);
ManagementEventWatcher=新的ManagementEventWatcher(managementScope,wqlEventQuery);
ManagementEventWatcher.EventArrized+=CDREventArrized;
ManagementEventWatcher.Start();
}
捕获(e)
{
Show(e.Message,e.GetType().ToString(),MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
私有void CdrEventArrived(对象发送方,EventArrivedEventArgs e)
{
var wmiDevice=(ManagementBaseObject)e.NewEvent[“TargetInstance”];
if(wmiDevice.Properties[“VolumeName”].Value!=null)
GetDrives();
其他的
GetDrives();
}
私有的void GetDrives()
{
如果(需要调用)
{
调用(新的getdriverselegate(GetDrives));
}
其他的
{
ToolStripComboxDrives.Items.Clear();
DriveInfo[]drives=DriveInfo.GetDrives();
_驱动器=新字典();
int selectedIndex=0;
foreach(驱动器信息驱动器输入驱动器)
{
if(drive.DriveType.Equals(DriveType.CDRom))
{
如果(驱动器已就绪)
{
string name=string.Format(“{0}({1})”,drive.VolumeLabel,drive.name.Substring(0,2));
int selectedDrive=toolstripcomboxdrives.Items.Add(name);
_驱动器。添加(名称、驱动器);
selectedIndex=selectedDrive;
}
其他的
{
ToolStripComboxDrives.Items.Add(drive.Name);
_drives.Add(drive.Name,drive);
}
}
}
ToolStripComboxDrives.SelectedIndex=SelectedIndex;
}
}

基本上,我正在做的是一个名为drivewatcher的表单加载事件。因此,当插入磁盘时,就绪磁盘将首先列在组合框中,用户可以轻松弹出驱动器。

请参阅以下代码:

foreach (DriveInfo drive in DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom))  
    MessageBox.Show(drive.Name + " " + drive.IsReady.ToString());  
参考链接:

foreach (DriveInfo drive in DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom))  
    MessageBox.Show(drive.Name + " " + drive.IsReady.ToString());  

堆栈链接:

foreach (DriveInfo drive in DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom))  
    MessageBox.Show(drive.Name + " " + drive.IsReady.ToString());  

参考以下代码:

foreach (DriveInfo drive in DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom))  
    MessageBox.Show(drive.Name + " " + drive.IsReady.ToString());  
参考链接:

foreach (DriveInfo drive in DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom))  
    MessageBox.Show(drive.Name + " " + drive.IsReady.ToString());  

堆栈链接:

foreach (DriveInfo drive in DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom))  
    MessageBox.Show(drive.Name + " " + drive.IsReady.ToString());  

您可以尝试使用以下代码:

public void networkDevice()
{
    try
    {
        WqlEventQuery q = new WqlEventQuery();
        q.EventClassName = "__InstanceModificationEvent";
        q.WithinInterval = new TimeSpan(0, 0, 1);
        q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5";

        ConnectionOptions opt = new ConnectionOptions();
        opt.EnablePrivileges = true;
        opt.Authority = null;
        opt.Authentication = AuthenticationLevel.Default;
        //opt.Username = "Administrator";
        //opt.Password = "";
        ManagementScope scope = new ManagementScope("\\root\\CIMV2", opt);

        ManagementEventWatcher watcher = new ManagementEventWatcher(scope, q);
        watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
        watcher.Start();
    }
    catch (ManagementException e)
    {
        Console.WriteLine(e.Message);
    }
}

void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
    ManagementBaseObject wmiDevice = (ManagementBaseObject)e.NewEvent["TargetInstance"];
    string driveName = (string)wmiDevice["DeviceID"];
    Console.WriteLine(driveName);
    Console.WriteLine(wmiDevice.Properties["VolumeName"].Value);
    Console.WriteLine((string)wmiDevice["Name"]);
    if (wmiDevice.Properties["VolumeName"].Value != null)
        Console.WriteLine("CD has been inserted");
    else
        Console.WriteLine("CD has been ejected");
}

如果它在您的计算机上工作,而在任何其他基于窗口的计算机上不工作,那么您必须重建/修复/重新注册该计算机的WMI类。这将对您有所帮助。

您可以尝试使用以下代码:

public void networkDevice()
{
    try
    {
        WqlEventQuery q = new WqlEventQuery();
        q.EventClassName = "__InstanceModificationEvent";
        q.WithinInterval = new TimeSpan(0, 0, 1);
        q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5";

        ConnectionOptions opt = new ConnectionOptions();
        opt.EnablePrivileges = true;
        opt.Authority = null;
        opt.Authentication = AuthenticationLevel.Default;
        //opt.Username = "Administrator";
        //opt.Password = "";
        ManagementScope scope = new ManagementScope("\\root\\CIMV2", opt);

        ManagementEventWatcher watcher = new ManagementEventWatcher(scope, q);
        watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
        watcher.Start();
    }
    catch (ManagementException e)
    {
        Console.WriteLine(e.Message);
    }
}

void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
    ManagementBaseObject wmiDevice = (ManagementBaseObject)e.NewEvent["TargetInstance"];
    string driveName = (string)wmiDevice["DeviceID"];
    Console.WriteLine(driveName);
    Console.WriteLine(wmiDevice.Properties["VolumeName"].Value);
    Console.WriteLine((string)wmiDevice["Name"]);
    if (wmiDevice.Properties["VolumeName"].Value != null)
        Console.WriteLine("CD has been inserted");
    else
        Console.WriteLine("CD has been ejected");
}

如果它在您的计算机上工作,而在任何其他基于窗口的计算机上不工作,那么您必须重建/修复/重新注册该计算机的WMI类。这将对您有所帮助。

我将采用以下解决方案。这是一个100%托管的解决方案。它没有使用WMI,工作得很好

internal class DriveWatcher
{
    public delegate void OpticalDiskArrivedEventHandler(Object sender, OpticalDiskArrivedEventArgs e);

    /// <summary>
    ///     Gets or sets the time, in seconds, before the drive watcher checks for new media insertion relative to the last occurance of check.
    /// </summary>
    public int Interval = 1;

    private Timer _driveTimer;

    private Dictionary<string, bool> _drives;

    private bool _haveDisk;

    /// <summary>
    ///     Occurs when a new optical disk is inserted or ejected.
    /// </summary>
    public event OpticalDiskArrivedEventHandler OpticalDiskArrived;

    private void OnOpticalDiskArrived(OpticalDiskArrivedEventArgs e)
    {
        OpticalDiskArrivedEventHandler handler = OpticalDiskArrived;
        if (handler != null) handler(this, e);
    }

    public void Start()
    {
        _drives = new Dictionary<string, bool>();
        foreach (
            DriveInfo drive in
                DriveInfo.GetDrives().Where(driveInfo => driveInfo.DriveType.Equals(DriveType.CDRom)))
        {
            _drives.Add(drive.Name, drive.IsReady);
        }
        _driveTimer = new Timer {Interval = Interval*1000};
        _driveTimer.Elapsed += DriveTimerOnElapsed;
        _driveTimer.Start();
    }

    public void Stop()
    {
        if (_driveTimer != null)
        {
            _driveTimer.Stop();
            _driveTimer.Dispose();
        }
    }

    private void DriveTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
    {
        if (!_haveDisk)
        {
            try
            {
                _haveDisk = true;
                foreach (DriveInfo drive in from drive in DriveInfo.GetDrives()
                                            where drive.DriveType.Equals(DriveType.CDRom)
                                            where _drives.ContainsKey(drive.Name)
                                            where !_drives[drive.Name].Equals(drive.IsReady)
                                            select drive)
                {
                    _drives[drive.Name] = drive.IsReady;
                    OnOpticalDiskArrived(new OpticalDiskArrivedEventArgs {Drive = drive});
                }
            }
            catch (Exception exception)
            {
                Debug.Write(exception.Message);
            }
            finally
            {
                _haveDisk = false;
            }
        }
    }
}

internal class OpticalDiskArrivedEventArgs : EventArgs
{
    public DriveInfo Drive;
}

我将使用以下解决方案。这是一个100%托管的解决方案。它没有使用WMI,工作得很好

internal class DriveWatcher
{
    public delegate void OpticalDiskArrivedEventHandler(Object sender, OpticalDiskArrivedEventArgs e);

    /// <summary>
    ///     Gets or sets the time, in seconds, before the drive watcher checks for new media insertion relative to the last occurance of check.
    /// </summary>
    public int Interval = 1;

    private Timer _driveTimer;

    private Dictionary<string, bool> _drives;

    private bool _haveDisk;

    /// <summary>
    ///     Occurs when a new optical disk is inserted or ejected.
    /// </summary>
    public event OpticalDiskArrivedEventHandler OpticalDiskArrived;

    private void OnOpticalDiskArrived(OpticalDiskArrivedEventArgs e)
    {
        OpticalDiskArrivedEventHandler handler = OpticalDiskArrived;
        if (handler != null) handler(this, e);
    }

    public void Start()
    {
        _drives = new Dictionary<string, bool>();
        foreach (
            DriveInfo drive in
                DriveInfo.GetDrives().Where(driveInfo => driveInfo.DriveType.Equals(DriveType.CDRom)))
        {
            _drives.Add(drive.Name, drive.IsReady);
        }
        _driveTimer = new Timer {Interval = Interval*1000};
        _driveTimer.Elapsed += DriveTimerOnElapsed;
        _driveTimer.Start();
    }

    public void Stop()
    {
        if (_driveTimer != null)
        {
            _driveTimer.Stop();
            _driveTimer.Dispose();
        }
    }

    private void DriveTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
    {
        if (!_haveDisk)
        {
            try
            {
                _haveDisk = true;
                foreach (DriveInfo drive in from drive in DriveInfo.GetDrives()
                                            where drive.DriveType.Equals(DriveType.CDRom)
                                            where _drives.ContainsKey(drive.Name)
                                            where !_drives[drive.Name].Equals(drive.IsReady)
                                            select drive)
                {
                    _drives[drive.Name] = drive.IsReady;
                    OnOpticalDiskArrived(new OpticalDiskArrivedEventArgs {Drive = drive});
                }
            }
            catch (Exception exception)
            {
                Debug.Write(exception.Message);
            }
            finally
            {
                _haveDisk = false;
            }
        }
    }
}

internal class OpticalDiskArrivedEventArgs : EventArgs
{
    public DriveInfo Drive;
}


您是否在基于windows的计算机上进行检查?是的,我的电脑有windows 8,但其他电脑有windows 7和windows 5(共1次),它会在告诉我插入磁盘时出错。您是否尝试过我的回答?是否按照您的建议验证WMI存储库。完成后更新问题。您是否在基于windows的计算机上进行检查?是的,我的电脑有windows 8,但其他电脑有windows 7和windows 5,但有1次它在告诉我插入磁盘时抛出错误。您是否尝试过我的回答?是否按照您的建议验证WMI存储库。完成后更新问题。重置WMI有效。但我认为有管理的解决方案将被证明比使用WMI更好。重置WMI很有效。但我认为有管理的解决方案将被证明比使用WMI更好。您的代码似乎没有按编写的方式执行。没有名为“DriveSystemWatcher”的类。调用OpticalDiskHandler大约需要10-12秒。。还有其他人面临类似的问题吗?我在应用程序中使用了此代码。另请参阅,您可以使用DriveWatcher类的interval参数调整轮询间隔。您的代码似乎没有按编写的方式执行。没有名为“DriveSystemWatcher”的类。调用OpticalDiskHandler大约需要10-12秒。。还有其他人面临类似的问题吗?我在应用程序中使用了此代码。另请参见,您可以使用DriveWatcher类的interval参数调整轮询间隔。