Search code examples
c#cmdexeargument-passing

Running EXE file form CMD made with C#


I'm newbie in c# and I'm stuck on this conundrum
I've recently made a Gui Program in c# that include several tabs and some other stuff Now I want to make one of the tabs as a exe file that i would be able to run via cmd . the entire code i want to put in file is comprised of one class something like that

class E2p
{
main program( take 2 arg )
{some Code


make a CSV file in appDirectory
}

I want to turn it to EXE file so I can run it from CMD like that

E2pChck.exe -i 10.0.0.127 -r RandomWord

How can I do it ??


Solution

  • I'm not 100% sure what you're after, but I think you mean that you want to be able to run your exe from the command line with a couple of arguments.

    These arguments are passed into your application in the Main method, which you'll find in Program.cs. In a command line application the arguments parameter is provided for you, but you can add it to a Windows Forms application.

    class Program
    {
        static void Main(string[] args)
        {
            string firstArgument;
            string secondArgument;
            const int NumberOfArgumentsRequired = 2;
    
            // you can access the arguments using the args array, 
            // but we need to make sure we have enough arguments, 
            // otherwise we'll get an index out of range exception 
            // (as we're trying to access items in an array that aren't there)
            if (args.Length >= NumberOfArgumentsRequired)
            {
                firstArgument = args[0];
                secondArgument = args[1];
            }
            else
            {
                // this block will be called if there weren't enough arguments
                // it's useful for setting defaults, although that could also be done
                // at the point where the strings were declared
                firstArgument = "This value was set because there weren't enough arguments.";
                secondArgument = "So was this one. You could do this at the point of declaration instead, if you wish.";
            }
    
            string outputString = string.Format("This is the first: {0}\r\nAnd this is the second: {1}", firstArgument, secondArgument);
            Console.WriteLine(outputString);
            Console.ReadKey();
        }
    }
    

    If you typed E2pChck.exe -i 10.0.0.127 -r RandomWord into the command line then:

    args[0] would be "-i"
    args[1] would be "10.0.0.127"
    args[2] would be "-r"
    args[3] would be "RandomWord"