如何编写一个类似这样的检查...如果任何(或者至少有一个)驱动器类型是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);
}
}
目前的问题是设置循环以首先单独设置每个驱动器。在一次驱动器检查不是CD-Rom之后,它会抛出一条错误消息并为每个驱动器执行此操作。我只想要一个统一的错误消息。
答案 0 :(得分:5)
我如何写一张类似这样的支票......如果有的话(或者 如果至少有一个驱动器类型是CDRom,那么真/继续...... else false(抛出错误)?
您可以尝试这样的事情:
// 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.
{
}
答案 1 :(得分:1)
你纠正LINQ可以提供帮助,事实上它可以大大缩短代码:
var readyCDRoms = DriveInfo.GetDrives().Any(drive =>
drive.DriveType == DriveType.CDRom && drive.IsReady);
foreach(var drive in readyCDRoms)
{
var file = new DirectoryInfo(drive.RootDirectory.Name)
.GetFiles(/* blah */).FirstOrDefault(); //only looking for the first one
if(file == null) continue; // No suitable files found
Debug.Print(file.FullName);
ImportCSV(file.FullName);
//Remove the break; to parse all CDROMS containing viable data
break;
}