Remove the last character if it's DirectorySeparatorChar with C#

fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar);

// If the fullPath is not a root directory
if (Path.GetDirectoryName(fullPath) != null)
    fullPath = fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

string path1 =  @"c:\directory\";
string path2 = @"c:\directory\file.txt";
string path3 = @"c:\directory";

Console.WriteLine(Path.Combine(Path.GetDirectoryName(path1), Path.GetFileName(path1)));
Console.WriteLine(Path.Combine(Path.GetDirectoryName(path2), Path.GetFileName(path2)));
Console.WriteLine(Path.Combine(Path.GetDirectoryName(path3), Path.GetFileName(path3)));

Gives:

c:\directory
c:\directory\file.txt
c:\directory

Hope it helps.

Tags:

C#

String