C# Code – getLastFolderName

By xerocube | June 22, 2006

I’ve recently developed the need for a function that would return the last folder name in a given string variable, containing a filepath. I am unaware of a inherent function provided by Microsoft that performs this functionality, so I wrote one myself.

—code snip—
/// <summary>
/// Returns the last folder name in a given file path.
/// </summary>
/// <param name=”strFilePath”>A string value containing a valid filepath.</param>
/// <returns>String value containing the last folder name of a file path.</returns>

getLastFolderName(string strFilePath)
    // declare variables
    char[] delimiters = {‘\\’};


    if (strFilePath.EndsWith(“\\”))
     //the provided filepath has a backslash at the end.
     //Removing the backslash.
     strFilePath = strFilePath.TrimEnd(delimiters);

    string[] folders = strFilePath.Split(delimiters);
   catch(Exception e)
    throw new Exception(“Unknown error in getLastFolderName().”, e);
—code snip—

Anyway — there it is… basic error handling, commentary, and support for file paths with and without the ending backslash. If anyone has improvements upon this code, let me know. Maybe someone will find it useful other than me…


Topics: Code, Tech | No Comments »