如何根据 WPF 中的给定字符串检查系统中是否存在驱动器。我尝试了以下方法
示例: FileLocation.Text = "K:\TestDrive\XXX";
if (!Directory.Exists(FileLocation.Text))
{
MessageBox.Show("Invalid Directory", "Error", MessageBoxButton.OK);
return;
}
它正在检查完整路径,但它应该检查文本中的“K:\”
。你能指导我吗
编辑 1:“K:\TestDrive\XXX”不是静态的
编辑 2: 我尝试了以下操作,在我的系统中我有 3 个驱动器 C、D 和 E
但它显示 false .
Environment.SystemDirectory.Contains("D").ToString(); = "False"
最佳答案
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;
}
当然,应该添加额外的健全性检查(路径根是否至少有三个字符,第二个是冒号),但这将作为练习留给读者。
关于c# - 检查驱动器是否存在(字符串路径),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17335072/