C# 如何知道给定路径是否代表根驱动器?

发布于 2024-10-17 21:14:00 字数 62 浏览 6 评论 0原文

我如何知道给定目录是否是根驱动器?

(除了检查其路径是否等于“A:”、“B:”、“C:”等)

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

无人接听 2024-10-24 21:14:00

检查DirectoryInfo.Parent是否为空,

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

您也可以使用DirectoryInfo.Root获取根;

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;

傲影 2024-10-24 21:14:00

尝试这个

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

Try this:

if (Path.GetPathRoot(location) == location) {...}
℡Ms空城旧梦 2024-10-24 21:14:00

这比检查 Parent 属性要复杂得多。

确定目录是否是已安装的文件夹

一种方法是查看GetVolumeNameForVolumeMountPoint 成功。

当然,这不适用于网络路径,可能无法远程确定网络驱动器是否代表分区的根目录。

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.

久伴你 2024-10-24 21:14:00

另外,这是我发现的另一种方法:

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

如果此函数返回 true,则意味着给定路径代表根驱动器!

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!

情魔剑神 2024-10-24 21:14:00

这是我发现的另一种方法:

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

这个方法实际上检查给定路径是否代表当前系统的逻辑驱动器之一。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文