Home > Blockchain >  How to get one up level folder name from a string?
How to get one up level folder name from a string?

Time:11-23

for exmaple if the path in the string textBoxRadarPath.txt is D:\test\test1\test2 i want to get only the part D:\test

using root is not what i needed root give me D:\ but i want to first path level.

Directory.CreateDirectory(Path.GetPathRoot(textBoxPath.Text)   "\\"   urlsListFolder);

CodePudding user response:

Try this function:

public string GetFirstLevel(string Path)
    {
        string[] Segments = Path.Split(Convert.ToChar(@"\"));

        return Segments[0]   @"\"   Segments[1];
    }

And here is an example of it's usage:

public void Test()
    {
        MessageBox.Show(GetFirstLevel(@"D:\test\test1\test2")); //It will return: D:\test
    }

CodePudding user response:

try this code:

string path = @"D:\test\test1\test2";
var Levels = path.Select((b, i) => b.Equals('\\') ? i : -1).Where(i => i != -1).ToList();

string newPath = path.Substring(0, Levels [1]);
Console.WriteLine(newPath);

result:

D:\test

  • Related