Check Drive Exists(string path)

前端 未结 8 943
半阙折子戏
半阙折子戏 2021-01-03 23:27

How to check the drive is exists in the system from the given string in WPF. I have tried the following

Ex: FileLocation.Text = \"K:\\TestDriv

相关标签:
8条回答
  • 2021-01-03 23:40

    This is Because Environment.SystemDirectory.XXXXX is all about where the system/windows is installed ...... not for whole HD.

    for this you can use.....

        foreach (var item in System.IO.DriveInfo.GetDrives())
        {
            MessageBox.Show(item.ToString());
        }
    

    it will show all drives including USBs that are attached.....

    0 讨论(0)
  • 2021-01-03 23:40

    You can check drives in C# like this

       foreach (var drive in DriveInfo.GetDrives())
       {
           //Code goes here
       }
    
    0 讨论(0)
  • 2021-01-03 23:42

    I suppose this depends on what exactly you are hoping to accomplish. If you are trying to iterate through the drives and test to make sure each drive exists, then Environment.GetLogicalDrives() or DriveInfo.GetDrives() is appropriate as it allows you to iterate through the drives.

    However, if all you care about is testing to see if ONE drive exists for a particular path, getting the entire list of drives to check if it is contained is a bit backwards. You would want to use Directory.Exists() as it just checks if that single path exists.

    bool DriveExists(string fileLocation) {
        string drive = Path.GetPathRoot(fileLocation); // To ensure we are just testing the root directory.
    
        return Directory.Exists(drive); // Does the path exist?
    }
    
    0 讨论(0)
  • 2021-01-03 23:48

    You can use Environment.GetLogicalDrives() to obtain an string[] of logical drives in your system.

    var drive = Path.GetPathRoot(FileLocation.Text);
    if (Environment.GetLogicalDrives().Contains(drive, StringComparer.InvariantCultureIgnoreCase))
    {
             MessageBox.Show("Invalid Directory", "Error", MessageBoxButton.OK);
             return;
    }
    
    0 讨论(0)
  • 2021-01-03 23:55
    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;
    }
    

    Of course, additional sanity checks (does the path root have at least three characters, is the second one a colon) should be added, but this will be left as an exercise to the reader.

    0 讨论(0)
  • 2021-01-03 23:57

    you can do follow

    bool isDriveExists(string driveLetterWithColonAndSlash)
    {
        return DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash);
    }
    
    0 讨论(0)
提交回复
热议问题