Is there any easy way to isolate the last 2 elements of the path (basedir filename) in C# or do I need to make some complex string regex? All examples I found online show either isolating the filename, or the full path minus filename.
Example of the input:
string1 = C:\dir\example\1\test.txt
string2 = C:\dir\example\2\anotherdir\example\file.ext
string3 = /mnt/media/hdd/test/1/2/3/4/dir/file
Expected output:
string1cut = 1\test.txt
string2cut = example\file.ext
string3cut = dir/file
CodePudding user response:
You can do this:
string path = @"C:\dir\example\1\test.txt";
string lastFolderName = Path.GetFileName(Path.GetDirectoryName(path));
string fileName = Path.GetFileName(path);
string string1Cut = @$"{lastFolderName}\{fileName}";
outputs : 1\test.txt
CodePudding user response:
You can split the paths into individual parts and then get the last 2 elements.
Implementation:
class Program
{
static void Main(string[] args)
{
var string1 = @"C:\dir\example\1\test.txt";
var string2 = @"C:\dir\example\2\anotherdir\example\file.ext";
var string3 = @"/mnt/media/hdd/test/1/2/3/4/dir/file";
var string1cut = GetLast2Elements(string1);
var string2cut = GetLast2Elements(string2);
var string3cut = GetLast2Elements(string3);
Console.WriteLine(string1cut);
Console.WriteLine(string2cut);
Console.WriteLine(string3cut);
}
static string GetLast2Elements(string path)
{
// determine the separator used in path
var delimiter = path.Contains(@"\") ? @"\" : "/";
// split path to parts using separator
var parts = path.Split(delimiter);
// get the last 2 elements
return $@"{parts[^2]}{delimiter}{parts.Last()}";
}
}
Output:
1\test.txt
example\file.ext
dir/file