Trailing slash(/) is added in arguments

2k views Asked by At

I'm registering a custom protocol handler on my computer, which calls this application:

        string prefix = "runapp://";

        // The name of this app for user messages
        string title = "RunApp URL Protocol Handler";

        // Verify the command line arguments
        if (args.Length == 0 || !args[0].StartsWith(prefix))
        { 
            MessageBox.Show("Syntax:\nrunapp://<key>", title); return; 
        }

        string key = args[0].Remove(0, "runapp://".Length);
        key.TrimEnd('/'); 

        string application = "";
        string parameters = "";
        string applicationDirectory = "";

        if (key.Contains("~"))
        {
            application = key.Split('~')[0];
            parameters = key.Split('~')[1];
        }
        else
        {
            application = key;
        }


        applicationDirectory = Directory.GetParent(application).FullName;

        ProcessStartInfo psInfo = new ProcessStartInfo();
        psInfo.Arguments = parameters;
        psInfo.FileName = application;

        MessageBox.Show(key + Environment.NewLine + Environment.NewLine + application + " " + parameters);
        // Start the application
        Process.Start(psInfo);

What it does is that it retrieves the runapp:// request, split it into two parts: application and the parameters passed, according to the location of the '~' character. (This is probably not a good idea if I ever pass PROGRA~1 or something, but considering I'm the only one using this, it's not a problem), then runs it.

However, a trailing '/' is always added to the string: if I pass

runapp://E:\Emulation\GameBoy\visualboyadvance.exe~E:\Emulation\GameBoy\zelda4.gbc, it will be interpreted as

runapp://E:\Emulation\GameBoy\visualboyadvance.exe E:\Emulation\GameBoy\zelda4.gbc/.

Why would it do this ? And why can't I get rid of this trailing slash ? I tried TrimEnd('/'), Remove(key.IndexOf('/'), 1), Replace("/", ""), yet the slash stays. What is happening ?

1

There are 1 answers

1
Polyfun On BEST ANSWER

You need to assign the result of the TrimEnd:

key = key.TrimEnd('/');

Strings in C# are immutable; therefore string methods which alter the string return a new string with the alterations, rather than changing the original string.