gpt4 book ai didi

驱动器的 C# 循环挂起

转载 作者:太空宇宙 更新时间:2023-11-03 11:17:54 24 4
gpt4 key购买 nike

我正在尝试查找驱动器的盘符(例如“C:\”)。我知道驱动器的名称(例如“KINGSTON”),并将其存储在字符串 drivename 中。sDir 是保存结果的字符串。

DriveInfo[] drives = DriveInfo.GetDrives();

foreach (DriveInfo d in drives)
{
MessageBox.Show(d.Name);
if (d.VolumeLabel.Contains(drivename))
{
MessageBox.Show("Got Ya");
sDir = d.Name;
break;
}
}

这段代码在我看来应该可以工作,尽管我有 6 个驱动器(drives.Lengt 也显示 6 个),但它只循环其中的 3 个,而没有进入 if(从不显示“got ya"msgbox),然后直接跳出if语句,这段代码被包裹了进去。

最佳答案

DriveInfo.VolumeLabel 可能会抛出异常,您必须妥善处理。 http://msdn.microsoft.com/library/system.io.driveinfo.volumelabel

DriveInfo[] drives = DriveInfo.GetDrives(); 

foreach (DriveInfo d in drives)
{
MessageBox.Show(d.Name);
string volumeLabel = null;
try
{
volumeLabel = d.VolumeLabel;
}
catch (Exception ex)
{
if (ex is IOException || ex is UnauthorizedAccessException || ex is SecurityException)
MessageBox.Show(ex.Message);
else
throw;
}
if (volumeLabel != null && volumeLabel.Contains(drivename))
{
MessageBox.Show("Got Ya");
sDir = d.Name;
break;
}
}

您还可以查看 DriveInfo.IsReady .

关于驱动器的 C# 循环挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12054245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com