Arlen Beiler
Arlen Beiler

Reputation: 15866

Parsing user input from a console as commandline arguments in c#

I need to split user input on spaces in a console application I am making, but I'm not quite sure how to do it. I can't just blindly split it because it will have quoted strings and stuff like that. What is a quick way to do this?

Or is there some way I can access the windows command-line parser and split it up using that?

Upvotes: 1

Views: 5504

Answers (5)

Arlen Beiler
Arlen Beiler

Reputation: 15866

Thanks to this answer, I finally got it. This checks for quotes, but does not worry about nested quotes. As per the comments to that answer, how is it going to know whether it is two quotes or nested quotes. You can't really go by spaces, because strings can start or end with spaces.

using System.Text.RegularExpressions;
...
Console.Write("Home>");
string command = Console.ReadLine();
Regex argReg = new Regex(@"\w+|""[\w\s]*""");
string[] cmds = new string[argReg.Matches(command).Count];
int i = 0;
foreach (var enumer in argReg.Matches(command))
{
    cmds[i] = (string)enumer.ToString();
    i++;
}

Upvotes: 0

NominSim
NominSim

Reputation: 8511

User input in a console application is simply: Console.ReadLine().

You may want to try something like this:

static void Main(string[] args)
{
    Console.WriteLine("Input please:");
    string input = Console.ReadLine();
    // Parse input with Regex (This splits based on spaces, but ignores quotes)
    Regex regex = new Regex(@"\w+|""[\w\s]*""");
}

Upvotes: 1

Pete
Pete

Reputation: 10871

Well, you have to build your own "transducer". Basically, in your main, you can just have a switch statement and a Console.ReadLine(). When the user runs your executable you can output something like Enter Command: and wait for the users input. Then just capture the users input and switch on it.

class Program
{
    static void Main(string[] args)
    {       
        string cmd = Console.ReadLine();
        switch(cmd)
        {
            case "DoStuff":
                someClass.DoStuff();
                break;
            case "DoThis":
                otherClass.DoThis();
                break;
        }       
    }
}

And if you want to continue receiving input commands from the user then just wrap something like that in a while loop and when the user wants to Quit break out of the loop and terminate the program.

Upvotes: 0

HELP_ME
HELP_ME

Reputation: 2729

To read the input as a string I would use:

string stringInput = Console.ReadLine();

Upvotes: 0

James
James

Reputation: 2841

When you create a new console application in Visual Studio, you get something like this:

class Program
{
    static void Main(string[] args)
    {
    }
}

The command line arguments passed in to the application will be in the 'args' parameter.

Upvotes: 3

Related Questions