Search code examples
c#indexoflastindexof

c# - is there anything like BeforeLastIndexOf?


I wanted to know if there is anything like "BeforeLastIndexOf". I'm new to c# and don't really know how "LastIndexOf" and "IndexOf" works. What I'm trying to achive is that for example the user types in a directory and it deletes from the string the last folder of this directory but usually directory's look like this "C:\something\something\" and it has a "\" at the end, so a code like this doesn't work:

string input = Console.ReadLine();
int index = input.LastIndexOf("/");
if (index > 0)
     input = input.Substring(0, index + 1);

Cause it deletes only everything after the last "\" and it's anyway at the end so it doesn't delete anything


Solution

  • It looks like you want to:

    1. Remove any trailing backslashes, using string.TrimEnd().
    2. Call Path.GetDirectoryName() to strip off the last directory.

    For example:

    string path1 = @"C:\something\something\";
    Console.WriteLine(Path.GetDirectoryName(path1.TrimEnd('\\'))); // Prints "C:\something
    
    string path2 = @"C:\something\something";
    Console.WriteLine(Path.GetDirectoryName(path2.TrimEnd('\\'))); // Prints "C:\something
    

    If you want to handle / characters too (since that's actually a valid path separator in Windows), you can just specify both in the TrimEnd():

    path1.TrimEnd('/', '\\')
    

    Thus:

    string path3 = @"C:/something/something//\\/";
    Console.WriteLine(Path.GetDirectoryName(path3.TrimEnd('/', '\\'))); // Prints "C:\something