How to Get Folder Name Without Full Path

Hello,

I would like to learn how to handle this more professionally.

Using a prompt, I ask the user to browse and select a folder (e.g., MyPC/Documents/Folder1/My_study ). I need to extract only the folder name (My_study ), not the full path.

At the moment, I’m using the Strlib library with overly complex logic.
I’m wondering if there is a simpler tool or method to achieve this.

Thanks a lot

1 Like

Not sure what you are exactly doing but it’s rather simple;
Use the HSL Extension String Library to convert your file path to an array and index the second last element; it’ll only be 5 lines of code

{
variable str_filePath, index;
variable arr_filePath[];
str_filePath  = "C:\\folder1\\file1.txt";

arr_filePath = HSLExtensions::String::Split(str_filePath,"\\", hslTrue);
index = arr_filePath.GetSize() - 2;

Trace("Last Folder:", arr_filePath[i]);
}
3 Likes

Hello,
I was wondering what is the correct way of doing it. Mine:

  • Get path lenght
  • Look for the last “\”
  • Perform path lenght - pos of last \
  • Add + 1 to account for the 0-based index
  • Use StrRight to only keep those characters

I found my logic very convoluted and coutner intuitive. This is why I was wondering if there is a better way of doing it.

Thank you

1 Like

Hi @KevinJ,

This can be done with the HSLExtensions File library. Both the commands GetFileName and GetFileNameWithoutExtension will function the same in your case. While they are technically in the “file” library they just return the last part of the specified string. So in the example below you would see “HSLExtensions” traced out.

image

image

Matt

4 Likes