Lou*_*hys 7 .net c# string path
如何在相对路径中获取第一个目录名,因为它们可以是不同的接受目录分隔符?
例如:
foo\bar\abc.txt -> foo
bar/foo/foobar -> bar
Run Code Online (Sandbox Code Playgroud)
jb.*_*jb. 10
好像你可以在字符串上使用string.Split()方法,然后抓住第一个元素.
示例(未经测试):
string str = "foo\bar\abc.txt";
string str2 = "bar/foo/foobar";
string[] items = str.split(new char[] {'/', '\'}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(items[0]); // prints "foo"
items = str2.split(new char[] {'/', '\'}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(items[0]); // prints "bar"
Run Code Online (Sandbox Code Playgroud)
适用于正斜杠和反斜杠
static string GetRootFolder(string path)
{
while (true)
{
string temp = Path.GetDirectoryName(path);
if (String.IsNullOrEmpty(temp))
break;
path = temp;
}
return path;
}
Run Code Online (Sandbox Code Playgroud)
最强大的解决方案是使用DirectoryInfo和FileInfo.在基于Windows NT的系统上,它应该接受分隔符的正斜杠或反斜杠.
using System;
using System.IO;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(GetTopRelativeFolderName(@"foo\bar\abc.txt")); // prints 'foo'
Console.WriteLine(GetTopRelativeFolderName("bar/foo/foobar")); // prints 'bar'
Console.WriteLine(GetTopRelativeFolderName("C:/full/rooted/path")); // ** throws
}
private static string GetTopRelativeFolderName(string relativePath)
{
if (Path.IsPathRooted(relativePath))
{
throw new ArgumentException("Path is not relative.", "relativePath");
}
FileInfo fileInfo = new FileInfo(relativePath);
DirectoryInfo workingDirectoryInfo = new DirectoryInfo(".");
string topRelativeFolderName = string.Empty;
DirectoryInfo current = fileInfo.Directory;
bool found = false;
while (!found)
{
if (current.FullName == workingDirectoryInfo.FullName)
{
found = true;
}
else
{
topRelativeFolderName = current.Name;
current = current.Parent;
}
}
return topRelativeFolderName;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9559 次 |
| 最近记录: |