Command line arguments being reformatted

Richard Rosenheim 86 Reputation points
2023-02-09T23:27:28.5533333+00:00

I'm starting to write a C# console app (using VS2022, and .NET 7.0) with the following sample command line:

 myapp text="some random text"

In args[], the parameter is showing up as:

 text=some random text

In the string returned by Environment.CommandLine, the command line (excluding the application path portion) is:

"text=some random text"

When parsed into args[], the quotes are being removed. When returned by Environment.CommandLine, the quotes are being moved to include the entire argument.

Is there a way of getting the command line without it being reformatted?

Developer technologies | .NET | Other
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

3 answers

Sort by: Most helpful
  1. Minxin Yu 13,506 Reputation points Microsoft External Staff
    2023-02-10T02:13:04.05+00:00

    Hi, Richard Rosenheim
    Double quotation marks (") is used to include spaces within an argument. For your reference: command line arguments

    Try text="\"some random text\""

            public static void Main(string[] args)
            {
    
                string[] arguments = Environment.GetCommandLineArgs();
                Console.WriteLine("GetCommandLineArgs: {0}", string.Join(", ", arguments));
            }
    

    User's image Output: User's image

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Richard Rosenheim 86 Reputation points
    2023-02-14T19:49:07.2+00:00

    Thanks for the replies. I appreciate your comments.

    But, to keep it simple for the end-users, and avoid them having to do things like double quotes, etc., I adjusted my code to just handle the command line as Windows is wanting to reformatting it.


  3. Karen Payne MVP 35,591 Reputation points Volunteer Moderator
    2023-02-14T21:06:29.2+00:00

    Quotes are removed from arguments, see the following code sample to place quotes in and how to traverse arguments.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.