开发者

How to get the Directories from the filepath excluding the root and filename

开发者 https://www.devze.com 2023-04-12 15:14 出处:网络
I have a filepath say \"C:\\hello\\hi\\dotnet\\abc.txt\". I just want the directories from the path. Expected Output :

I have a filepath say "C:\hello\hi\dotnet\abc.txt". I just want the directories from the path.

Expected Output :

hello
hi
dotnet

I have used Path.DirectorySeparatorChar but it doesn't work.So help me out to solve th开发者_运维技巧is problem.


use (EDIT as per comments)

string YourFilePath = @"C:\hello\hi\dotnet\abc.txt";
string[] YourResult = Path.GetDirectoryName (YourFilePath).Split (new char[] {Path.DirectorySeparatorChar}).Skip(1).ToArray();

And this is the result:

YourResult[0] contains hello
YourResult[1] contains hi
YourResult[2] contains dotnet

For MSDN references see:

  • http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx
  • http://msdn.microsoft.com/en-us/library/system.io.path.directoryseparatorchar.aspx
  • http://msdn.microsoft.com/en-us/library/b873y76a.aspx
  • http://msdn.microsoft.com/en-us/library/bb358985.aspx
  • http://msdn.microsoft.com/en-us/library/bb298736.aspx


How about using string.Split and ignore the first and last items in the array?


How about: -

string filename = @"C:\hello\hi\dotnet\abc.txt";
string dirName = Path.GetDirectoryName(filename);   // C:\hello\hi\dotnet
string pathRoot = Path.GetPathRoot(dirName);        // C:\
string result = dirName.Substring(pathRoot.Length); // hello\hi\dotnet


You can use this function

IEnumerable<string> GetDirectories(string path)
{                        
    DirectoryInfo di = new DirectoryInfo(path);

    yield return di.Name;
    if (di.Parent == null)
       yield break;
    foreach (var dir in GetDirectories(di.Parent.FullName))
    {
       yield return dir;
    }           
}

using:

string path = Assembly.GetExecutingAssembly().Location;
foreach(var dir in GetDirectories(path).Reverse())
      Console.WriteLine(dir);


foreach (string s in System.IO.Path.GetDirectoryName (path).Split(System.IO.Path.DirectorySeparatorChar).Skip(1))
{
   //output
}


You Can Do

string filePath="C:\\DocumentsAndSettings\\Users\\Xyz\\Downloads\\abc.txt";
filePath=Path.GetFullPath(filePath);
var split =filePath.Split('\\');
var sp = split.Take(split.Length - 1);
foreach ( var st in sp)
{
     Console.WriteLine(st);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消