Skip to main content

C# method to strip/remove trailing slashes from a string (normally a path or URI/URL).

void Main()
{
    string withSlashes = @"//\\//";

    Console.WriteLine($"With Trailing Slashes: '{withSlashes}'");
    Console.WriteLine($"Trailing Slashes Stripped: '{StripTrailingSlashes(withSlashes)}'");

    // >> With Trailing Slashes.......: '//\\//'
    // >> Trailing Slashes Stripped...: ''
}

/// <summary>
/// Strip trailing slashes (both forward and or back slashes, or combination of) from the specified <paramref name="path"/>.
/// </summary>
/// <param name="path">A file system path or URI/URL with trailing slashes.</param>
/// <returns>A string with the trailing slashes removed. If a null or empty string is specified in the <paramref name="path"/> parameter, <paramref name="path"/> is immediately returned with null or empty (respectively).</returns>
public static string StripTrailingSlashes(string path)
{
    if (string.IsNullOrEmpty(path))
    {
        return path;
    }

    const char backSlash = '\\';
    const char forwardSlash = '/';

    if (path.EndsWith(backSlash.ToString(), StringComparison.Ordinal)
        || path.EndsWith(forwardSlash.ToString(), StringComparison.Ordinal))
    {
        int lastSlashPosition;
        while ((lastSlashPosition = path.IndexOf(backSlash, path.Length - 1)
                                    & path.IndexOf(forwardSlash, path.Length - 1)) > -1)
        {
            if (path.Length == 1)
            {
                // last remaining char... if it's a slash, remove it:
                if (path.IndexOf(backSlash) > -1 || path.IndexOf(forwardSlash) > -1)
                {
                    path = path.Substring(0, 0);
                }

                break;
            }

            path = path.Substring(0, lastSlashPosition);
        }
    }

    return path;
}