[英]How to get the root directory
I have a file path as 我有一个文件路径
D:\Accurev\PPF6-AvailableToUse_Test_4_4\eBizSol_App\Source\xyz.txt
If I do 如果我做
Path.GetDirectoryName(fileName)
I get 我懂了
D:\Accurev\PPF6-AvailableToUse_Test_4_4\eBizSol_App\Source
But I want to get only the root directory ie "D:\\\\"
但我只想获取根目录,即
"D:\\\\"
How can I get it? 我怎么才能得到它?
NB~ Is it possible without string splitting? NB〜是否可以不分割字符串?
Use Path.GetPathRoot method provided by the framework 使用框架提供的Path.GetPathRoot方法
Gets the root directory information of the specified path
获取指定路径的根目录信息
For your case you can use: 对于您的情况,您可以使用:
string rootPath = Path.GetPathRoot(filename);
String pathname= @"D:\Accurev\PPF6-AvailableToUse_Test_4_4\eBizSol_App\Source\xyz.txt";
string root = Path.GetPathRoot(pathname);
You're in luck, there're several ways to do the same thing. 您很幸运,有几种方法可以完成相同的操作。 Here're two of them:
这是其中两个:
Path.GetRootPath as other answers already shown Path.GetRootPath作为其他答案已经显示
DirectoryInfo.Root property of FileInfo
class: FileInfo
类的DirectoryInfo.Root属性:
var fileName= @"D:\\Accurev\\PPF6-AvailableToUse_Test_4_4\\eBizSol_App\\Source\\xyz.txt"; var file=new FileInfo(fileName); var root=file.Directory.Root;
You can use Path.GetPathRoot
Method for this. 您可以为此使用
Path.GetPathRoot
方法。
So, you can simply have string root = Path.GetPathRoot(fullFileName);
因此,您可以简单地使用
string root = Path.GetPathRoot(fullFileName);
But , this method does not verify that the path or file name exists. 但是 ,此方法不能验证路径或文件名是否存在。
Possible patterns for the string returned by this method are on MSDN as follows: 在MSDN上,此方法返回的字符串的可能模式如下:
"/"
(path specified an absolute path on the current drive). "/"
(路径指定了当前驱动器上的绝对路径)。 "X:"
(path specified a relative path on a drive, where X represents a drive or volume letter). "X:"
(路径指定驱动器上的相对路径,其中X表示驱动器或卷号)。 "X:/"
(path specified an absolute path on a given drive). "X:/"
(路径指定了给定驱动器上的绝对路径)。 "\\\\ComputerName\\SharedFolder"
(a UNC path). "\\\\ComputerName\\SharedFolder"
(UNC路径)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.