如何检查系统中的驱动器 [英] how to check drives in a system
问题描述
我必须检查系统中是否存在Z驱动器。如果存在Z潜水,我需要传递SourceFolder =Z:\\ test。只有当机器中没有Z驱动器时,我才需要传递SourceFolder =C:\\ test。我尝试了下面提到的代码,但由于系统有默认的C驱动器,它总是只采用SourceFolder =C:\\ test。
<预郎= C#> DriveInfo [] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
int i = allDrives.Count();
string aa = d.Name;
if (d.Name.Contains( Z:\\))
{
SourceFolder = Z:\\test
}
else
{
SourceFolder = C:\\test
}
}
请协助。
提前致谢
使用 System.Linq;
DriveInfo [] allDrives = DriveInfo.GetDrives();
SourceFolder =(allDrives.Any(d = > d.Name.StartsWith( Z:)))
? @ Z:\ test
: @ C:\ test;
应该有效。
我使用@
来避免在字符串中转义反斜杠。
希望这会有所帮助。
除了phil.o解决方案之外,如果驱动器搜索在找到肯定结果时停止搜索,那么您的解决方案会更好。目前,您的代码始终返回已检查的最终驱动器的路径。
foreach (DriveInfo d in allDrives)
{
int i = allDrives.Count();
string aa = d.Name;
if (d.Name.Contains( Z:\\))
{
SourceFolder = Z:\\ test
break ; <跨度类= 代码注释> // 跨度> <跨度类= 代码注释> ---加入此--- 跨度>
}
<跨度类=code-keyword> else
{
SourceFolder = C: \\test
}
}
首先尝试找到你的Z-Drive:< br $> b $ b
bool bFound = 假跨度>;
foreach (DriveInfo d in allDrives)
{
int i = allDrives.Count();
string aa = d.Name;
if (d.Name.Contains( Z:\\))
{
bFound = true ;
break ;
}
}
如果(bFound)
{
SourceFolder = Z:\\ test;
}
else
{
SourceFolder = C:\\ test;
}
I have to check if "Z" drive is present in a system. if "Z" dive is present i need to pass SourceFolder = "Z:\\test". Only if there is no Z drive in the machine i need to pass SourceFolder = "C:\\test". I have tried the below mentioned code but as the system having default C drive it is always taking only SourceFolder = "C:\\test".
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
int i = allDrives.Count();
string aa = d.Name;
if (d.Name.Contains("Z:\\"))
{
SourceFolder = "Z:\\test"
}
else
{
SourceFolder = "C:\\test"
}
}
Please assist.
Thanks in advance
using System.Linq; DriveInfo[] allDrives = DriveInfo.GetDrives(); SourceFolder = (allDrives.Any(d => d.Name.StartsWith("Z:"))) ? @"Z:\test" : @"C:\test";
should work.
I used the@
to avoid escaping backslashes inside the strings.
Hope this helps.
Apart from the phil.o solution, your solution would work a lot better if the drive search stopped when it found a positive result. At the moment, your code always returns the path from the final drive checked.
foreach (DriveInfo d in allDrives) { int i = allDrives.Count(); string aa = d.Name; if (d.Name.Contains("Z:\\")) { SourceFolder = "Z:\\test" break; // --- Add this --- } else { SourceFolder = "C:\\test" } }
Try to find first your Z-Drive like this:
bool bFound = false; foreach (DriveInfo d in allDrives) { int i = allDrives.Count(); string aa = d.Name; if (d.Name.Contains("Z:\\")) { bFound = true; break; } } if (bFound) { SourceFolder = "Z:\\test"; } else { SourceFolder = C:\\test; }
这篇关于如何检查系统中的驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!