2

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
Priora
  • 23
  • 3
  • Does this answer your question? [Getting the folder name from a full filename path](https://stackoverflow.com/questions/3736462/getting-the-folder-name-from-a-full-filename-path) – Rafal Oct 22 '22 at 04:56
  • Does this answer your question? [How to get relative path from absolute path](https://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path) – Klaus Gütter Oct 22 '22 at 05:31

1 Answers1

2

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

mathis1337
  • 1,426
  • 8
  • 13
  • For `/mnt/media/hdd/test/1/2/3/4/dir/file` your solution gives `dir\file` instead of the `dir/file` as mentioned in question – Ibrahim Timimi Oct 22 '22 at 05:15
  • added a quick slash check in the path to use now. Not the cleanest but gets the job done. – mathis1337 Oct 22 '22 at 05:43
  • 1
    Using that takes the separator from the machine environment so it would be wrong on certain links, since the OP posted two different kinds, but they will exist in one environment you have to take it from the string URL instead to be safe. – mathis1337 Oct 22 '22 at 18:40
  • Agreed. Using the Path.DirectorySeparatorChar will return the pathing slash from the machine its being called on, so its not safe to use here since OP showed two different kinds of pathing. – TravTanker Oct 22 '22 at 18:42