0

Was just wondering whether there is a way to read in commandlines in a console app with values. I can read in commandlines easily enough but can't seem to find any info about obtaining values from a commandline.

For example(args):

aTest = 5; bTest = 13; 

Would there be a way to read in the arg aTest an associate it with the int 5...?

Thanks :)

1
  • 2
    Did you try something to parse those values? What results do you have now? Commented Jun 1, 2015 at 9:24

2 Answers 2

2

I have written a helper method for me along time ago, which extracts the value of a swtich or returns if present or not - this will help you maybe.

/// <summary> /// If the arguments are in the format /member=value /// Than this function returns the value by the given membername (!casesensitive) (pass membername without '/') /// If the member is a switch without a value and the switch is preset the given ArgName will be returned, so if switch is presetargname means true.. /// </summary> /// <param name="args">Console-Arg-Array</param> /// <param name="ArgName">Case insensitive argname without /</param> /// <returns></returns> private static string getArgValue(string[] args, string ArgName) { var singleFound = args.Where(w => w.ToLower() == "/" + ArgName.ToLower()).FirstOrDefault(); if (singleFound != null) return ArgName; var arg = args.Where(w => w.ToLower().StartsWith("/" + ArgName.ToLower() + "=")).FirstOrDefault(); if (arg == null) return null; else return arg.Split('=')[1]; } 

Example:

static void Main(string[] args) { var modeSwitchValue = getArgValue(args, "mode"); if (modeSwitchValue == null) { //Argument not present return; } else { //do something } } 
Sign up to request clarification or add additional context in comments.

3 Comments

Ah nice- thanks! arg.Split I wasn't aware of this function! Thanking you :):) c# nub :/
@Anonagon if it fits your requirements - mark as answer plz ;)
Why not move the statements into the FirstOrDefault? args.FirstOrDefault(w => w.ToLower() == "/" + ArgName.ToLower()); should yield the same result, same with the second statement.
0

This works find for your input as provided:

var args = "aTest = 5; bTest = 13;"; var values = args .Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim().Split('=').Select(y => y.Trim()).ToArray()) .ToDictionary(x => x[0], x => int.Parse(x[1])); 

I get this result:

result

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.