使用C#从CMD运行EXE文件

时间:2014-02-24 19:09:33

标签: c# cmd exe argument-passing

我是c#的新手,我陷入了这个难题 我最近在c#中制作了一个包含几个标签和其他东西的Gui程序 现在我想将其中一个选项卡作为exe文件,我可以通过cmd运行。 我想要放入文件的整个代码由一个类组成 类似的东西

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


make a CSV file in appDirectory
}

我想把它变成EXE文件,所以我可以像那样从CMD运行它

E2pChck.exe -i 10.0.0.127 -r RandomWord

我该怎么办?

2 个答案:

答案 0 :(得分:2)

我不是100%肯定你所追求的是什么,但我认为你的意思是你希望能够通过一些参数从命令行运行你的exe。

这些参数以Main方法传递到您的应用程序中,您可以在Program.cs中找到它。在命令行应用程序中,为您提供了arguments参数,但您可以将其添加到Windows窗体应用程序中。

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();
    }
}

如果在命令行中键入E2pChck.exe -i 10.0.0.127 -r RandomWord,则:

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

我希望这对你有所帮助。

答案 1 :(得分:0)

我知道这在技术上没有回答这个问题,但OP要求提供一个启动流程的例子。

您可以将此代码放在按钮处理程序中(可能在单独的线程中,因此您的UI不会挂起)

    System.Diagnostics.ProcessStartInfo csvGenerationProcInfo = new System.Diagnostics.ProcessStartInfo();
    csvGenerationProcInfo.Arguments = "-i 10.0.0.127 -r RandomWord";
    csvGenerationProcInfo.FileName = "E2pChck.exe";

    System.Diagnostics.Process csvGenerationProc = System.Diagnostics.Process.Start(csvGenerationProcInfo);
    csvGenerationProc.WaitForExit();

或者,如果您不需要ProcessStartInfo的所有功能,您可以使用:

System.Diagnostics.Process.Start("E2pChck.exe", "-i 10.0.0.127 -r RandomWord");

希望有所帮助!