Priora
Priora

Reputation: 23

Getting the basedir and filename from a path in C#

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

Upvotes: 2

Views: 218

Answers (1)

mathis1337
mathis1337

Reputation: 1629

You can do this:

string path = @"C:\dir\example\1\test.txt";
string path2 = @"/mnt/media/hdd/test/1/2/3/4/dir/file";
string lastFolderName = 
Path.GetFileName(Path.GetDirectoryName(path));
string fileName =  Path.GetFileName(path);
string envPathChar = path.Contains("/") ? "/" : @"\";

string string1Cut = @$"{lastFolderName}{envPathChar}{fileName}";

outputs : 1\test.txt

path2 outputs : dir/file

Upvotes: 2

Related Questions