Kal*_*a J 1 c# boolean driveinfo any
如何编写一个类似这样的检查...如果任何(或至少一个)驱动器类型是CDRom,那么真/继续......否则为假(抛出错误)?
现在,我为每个不通过CDRom要求的驱动器检查抛出了错误.我想我需要使用Any()的LINQ查询,但我不断收到错误.我可能没有正确地写它.
我的计划是在以下情况下抛出错误消息:
- 没有输入CD
- 计算机上没有CD-ROM驱动器
-CD输入为空白
-CD输入不包含所需的特定文件
到目前为止,这是我所希望的方式:
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
Console.WriteLine("Drive {0}", d.Name);
Console.WriteLine(" File type: {0}", d.DriveType);
if (d.IsReady == true && d.DriveType == DriveType.CDRom)
{
DirectoryInfo di = new DirectoryInfo(d.RootDirectory.Name);
var file = di.GetFiles("*.csv", SearchOption.AllDirectories).FirstOrDefault();
if (file == null)
{
errorwindow.Message = LanguageResources.Resource.File_Not_Found;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
else
{
foreach (FileInfo info in di.GetFiles("*.csv", SearchOption.AllDirectories))
{
Debug.Print(info.FullName);
ImportCSV(info.FullName);
break; // only looking for the first one
}
}
}
else
{
errorwindow.Message = LanguageResources.Resource.CDRom_Error;
dialogService.ShowDialog(LanguageResources.Resource.Error, errorWindow);
}
}
Run Code Online (Sandbox Code Playgroud)
目前的问题是设置循环以首先单独设置每个驱动器.在一次驱动器检查不是CD-Rom之后,它会抛出一条错误消息并为每个驱动器执行此操作.我只想要一个统一的错误消息.
如何编写一个类似这样的检查...如果任何(或至少一个)驱动器类型是CDRom,那么真/继续......否则为假(抛出错误)?
你可以尝试这样的事情:
// Get all the drives.
DriveInfo[] allDrives = DriveInfo.GetDrives();
// Check if any cdRom exists in the drives.
var cdRomExists = allDrives.Any(drive=>drive.DriveType==DriveType.CDRom);
// If at least one cd rom exists.
if(cdRomExists)
{
// Get all the cd roms.
var cdRoms = allDrives.Where(drive=>drive.DriveType==DriveType.CDRom);
// Loop through the cd roms collection.
foreach(var cdRom in cdRoms)
{
// Check if a cd is in the cdRom.
if(cdRom.IsReady)
{
}
else // the cdRom is empty.
{
}
}
}
else // There isn't any cd rom.
{
}
Run Code Online (Sandbox Code Playgroud)