如何获取一个文件夹的根目录+1?
示例:
输入:C:\Level1\Level2\level3
输出应该是:
Level1
如果输入是Level1
,输出应为Level1
如果输入是C:\,输出应为空字符串
是否有一个.NET函数可以处理这个问题?
Directory.GetDirectoryRoot
始终返回C:\
Path
类、Substring
和 Split
方法来移除根目录并获取顶层文件夹。// your directory:
string dir = @"C:\Level1\Level2\level3";
// C:\
string root = Path.GetPathRoot(dir);
// Level1\Level2\level3:
string pathWithoutRoot = dir.Substring(root.Length);
// Level1
string firstFolder = pathWithoutRoot.Split(Path.DirectorySeparatorChar).First();
另一种方法是使用 DirectoryInfo
类及其 Parent
属性:
DirectoryInfo directory = new DirectoryInfo(@"C:\Level1\Level2\level3");
string firstFolder = directory.Name;
while (directory.Parent != null && directory.Parent.Name != directory.Root.Name)
{
firstFolder = directory.Parent.Name;
directory = directory.Parent;
}
然而,我更喜欢“轻量级”的字符串方法。
string dir = @"C:\foo\bar\woah";
var dirSegments = dir.Split(new char[] { Path.DirectorySeparatorChar },
StringSplitOptions.RemoveEmptyEntries);
if (dirSegments.Length == 1)
{
return string.Empty;
}
else
{
return dirSegments[0] + Path.DirectorySeparatorChar + dirSegments[1];
}
AltDirectorySeparatorChar
。 - R. Martinho Fernandesstring path = "C:\Level1\Level2\level3";
DirectoryInfo d = new DirectoryInfo(path);
while (d.Parent.FullName != Path.GetPathRoot(path))
{
d = d.Parent;
}
return d.FullName;
DirectoryInfo
和while
循环。DirectoryInfo info = new DirectoryInfo(path);
while (info.Parent != null && info.Parent.Parent != null)
info = info.Parent;
string result = info.FullName;
一种可能的解决方案,但不一定是最好的,是找到@"\"的位置,并进行一些手动处理。下面的代码没有完全测试,只是片段:
//var positions = inputString.IndexOfAny(new [] {'\'}); //Original one
//Updated, thanks to Snixtor's implementation
var positions = inputString.IndexOfAny(new [] {Path.DirectorySeparatorChar});
int n=positions.Length;
if(n>=1)
{
var pos = positions[1]; //The 2nd '\';
return inputString.SubString(0, pos);
}
return null;
string level1_2 = Directory.GetDirectoryRoot(path) + path.Split(Path.DirectorySeparatorChar).Skip(1).Take(1).DefaultIfEmpty("").First();
为什么不直接使用System.IO.Path
来获取名称呢?
MessageBox.Show(System.IO.Path.GetFileName(
System.IO.Path.GetDirectoryName(
System.IO.Path.GetDirectoryName(@"C:\Level1\Level2\Level3")
)
));
这将返回一级
。
MessageBox.Show(System.IO.Path.GetFileName(
System.IO.Path.GetDirectoryName(
System.IO.Path.GetDirectoryName(@"C:\")
)
));
这会返回一个空字符串。
不确定这是否是正确的方式,但你可以这样做:
string s = @"C:\Level1\Level2\Level3";
string foo = s.split(@"\")[1];
不确定 DirectoryInfo 对象是否可以以更简洁的方式获取此内容。
DirectoryInfo di = new DirectoryInfo(@"C:\Level1\Level2\Level3");
di.Root;
di.Root
将返回"C:"。 - Hans Kesting var di = new System.IO.DirectoryInfo(@"C:\a\b\c");
Func<DirectoryInfo, DirectoryInfo> root = null;
root = (info) => info.Parent.FullName.EndsWith("\\") ? info : root(info.Parent);
var rootName = root(di).Name; //#a