开发者

Why does Environment.CommandLine.Trim('"') not remove the trailing quote?

The following C# code:

using System;
namespace TrimTest {
    class 开发者_开发技巧Program {
        static void Main(string[] args) {
            Console.WriteLine(Environment.CommandLine);
            Console.WriteLine(Environment.CommandLine.Trim('"'));
            Console.ReadKey(false);
        }
    }
}

produces the following output:

"D:\Projects\TrimTest\TrimTest\bin\Debug\TrimTest.vshost.exe"
D:\Projects\TrimTest\TrimTest\bin\Debug\TrimTest.vshost.exe"

Unless I'm misreading the documentation:

The string that remains after all occurrences of the characters in the trimChars parameter are removed from the start and end of the current String object. If trimChars is null or an empty array, white-space characters are removed instead.

shouldn't the trailing double-quote be trimmed from the second string in that output?


It looks like you could be running in to a situation where there's trailing whitespace after the last double quote.

Try:

Console.WriteLine(Environment.CommandLine.Trim().Trim('"'));

And see what happens.

You could also pass extra characters in the parameter array to the overload you're already using:

Console.WriteLine(Environment.CommandLine.Trim('"', ' '));

But since I don't know what kind of whitespace there is, I prefer to use the overload that removes ALL whitespace rather than guess which character is there.


As alluded to by Justin, trailing whitespace is the issue. Try this:

Console.WriteLine(Environment.CommandLine.Trim( new[] {'"', ' '} ));


It removes from the very start and end, but in your case u cant see that there is a white space too =) ion15.vshost.exe"


Turns out there's a space at the very end:

        Console.WriteLine(Environment.CommandLine);
        Console.WriteLine(Environment.CommandLine.Trim('"'));

This one works:

        string commandLine = Environment.CommandLine.Trim(new char[] {'"', ' '});
        Console.WriteLine(commandLine);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜