检查驱动器是否存在(字符串路径)

Pon*_*lar 15 c# wpf

如何检查驱动器是否存在于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)

当然,应该添加额外的健全性检查(路径根目录中至少有三个字符,第二个是冒号),但这将留给读者练习.

  • [Path.GetPathRoot](http://msdn.microsoft.com/en-us/library/system.io.path.getpathroot.aspx)优于子串... (2认同)
  • @Ponmalar:`\\\\`不是驱动器,所以*应该*失败.请注意[GetPathRoot适用于UNC路径](http://stackoverflow.com/q/4230112/87698)! (2认同)
  • 遗憾的是,此方法不适用于已存在但不含介质的驱动器(例如不含 CD 的 CD-ROM 驱动器)。即,该方法将驱动器显示为不可访问,但不允许确定驱动器号是否可用或已被占用(驱动器“存在”)。 (2认同)

Dre*_*ild 5

你可以按照

bool isDriveExists(string driveLetterWithColonAndSlash)
{
    return DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash);
}
Run Code Online (Sandbox Code Playgroud)