在参数中添加尾部斜杠(/)

pik*_*zen 3 c# protocols url-protocol

我正在我的计算机上注册一个自定义协议处理程序,它调用此应用程序:

        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);
Run Code Online (Sandbox Code Playgroud)

它的作用是检索runapp://请求,将其拆分为两部分:应用程序和传递的参数,根据'〜'字符的位置.(如果我通过PROGRA~1或其他东西,这可能不是一个好主意,但考虑到我是唯一使用它的人,这不是问题),然后运行它.

但是,始终在字符串中添加尾随的'/':如果我通过

runapp://E:\Emulation\GameBoy\visualboyadvance.exe~E:\Emulation\GameBoy\zelda4.gbc,它将被解释为

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

它为什么要这样做?为什么我不能摆脱这个尾随斜线?我试过TrimEnd('/'),Remove(key.IndexOf('/'), 1),Replace("/", ""),但斜线停留.怎么了 ?

Pol*_*fun 5

您需要分配TrimEnd的结果:

key = key.TrimEnd('/');
Run Code Online (Sandbox Code Playgroud)

C#中的字符串是不可变的 ; 因此,更改字符串的字符串方法会返回带有更改的新字符串,而不是更改原始字符串.