C# How to know if a given path represents a root drive?

為{幸葍}努か 提交于 2019-12-06 16:39:41

问题


How can I know if a given directory is a root drive?

(aside from checking if its path equals to "A:", "B:", "C:", etc.)


回答1:


Check if DirectoryInfo.Parent is null or not

DirectoryInfo d = new DirectoryInfo("");
if(d.Parent == null) { IsRoot = true; }

you can also get the root by using DirectoryInfo.Root;




回答2:


It's much more complicated than checking the Parent property.

Determining Whether a Directory Is a Mounted Folder

One approach would be to see if GetVolumeNameForVolumeMountPoint succeeds.

Of course that won't work for network path, determining if a network drive represents the root directory of a partition may not be possible remotely.




回答3:


Try this:

if (Path.GetPathRoot(location) == location) {...}



回答4:


Also Here's another way I found:

 public static bool IsLogicalDrive(string path)
 {
     return (new DirectoryInfo(path).FullName == new DirectoryInfo(path).Root.FullName);
 }

if this function returns true, then it means that given path represents a root drive!




回答5:


Here's another way I found:

public static bool IsLogicalDrive(string path)
{
    return Directory.GetLogicalDrives().Contains(path);
}

This one actually checks if the given path represents one of the current system's logical drives.



来源:https://stackoverflow.com/questions/5047570/c-sharp-how-to-know-if-a-given-path-represents-a-root-drive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!