如何检查驱动器是否存在于WPF中给定字符串的系统中.我尝试了以下内容
例如: FileLocation.Text = "K:\TestDrive\XXX";
if (!Directory.Exists(FileLocation.Text))
{
MessageBox.Show("Invalid Directory", "Error", MessageBoxButton.OK);
return;
}
Run Code Online (Sandbox Code Playgroud)
它正在检查完整路径但是it should check "K:\" from the text
.你能指导我吗?
编辑1: " K:\ TestDrive\XXX "不是静态的
编辑2:我尝试了下面的,在我的系统中,我有,3 drives C, D and E
但它显示错误.
Environment.SystemDirectory.Contains("D").ToString(); = "False"
Run Code Online (Sandbox Code Playgroud)
Hei*_*nzi 30
string drive = Path.GetPathRoot(FileLocation.Text); // e.g. K:\
if (!Directory.Exists(drive))
{
MessageBox.Show("Drive " + drive + " not found or inaccessible",
"Error", MessageBoxButton.OK);
return;
}
Run Code Online (Sandbox Code Playgroud)
当然,应该添加额外的健全性检查(路径根目录中至少有三个字符,第二个是冒号),但这将留给读者练习.
你可以按照
bool isDriveExists(string driveLetterWithColonAndSlash)
{
return DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
29023 次 |
最近记录: |