简体   繁体   English

如何使用批处理文件中的参数运行c#应用程序

[英]How to run a c# application with arguments from a batch file

I have a C# project that takes in arguments that I'm trying to run from a bat file. 我有一个C#项目,它接受我试图从bat文件运行的参数。 For an application that doesn't take arguments I just put the following inside a file called run.bat 对于不带参数的应用程序,我只需将以下内容放在名为run.bat的文件中

pathname\helloworld\bin\Debug\helloworld.exe 

What if my program takes in parameters, how do I adjust. 如果我的程序接收参数怎么办,我该如何调整。 When is the echo of used? 什么时候使用回声? any good tutorial on writing batch files? 关于编写批处理文件的任何好教程? Thanks 谢谢

pathname\helloworld\bin\Debug\helloworld.exe "argument 1" "argument 2" 3

using System;
public class Demo {
    public static void Main(string[] args) {
        foreach(string arg in args)
            Console.WriteLine(arg);
    }
}

I would try 我会尝试

@rem turn off echo - atsign is line-level way how to do it
@echo off
@rem provided your app takes three params, this is how to pass them to exe file
pathname\helloworld\bin\Debug\helloworld.exe %1 %2 %3

String arguments tend to just follow the EXE after a space. 字符串参数倾向于在空格后跟随EXE。 So if you have two parameters "Bob", and "is a jerk" you could write this in the .bat: 因此,如果您有两个参数“Bob”,并且“是一个混蛋”,您可以在.bat中写这个:

helloworld.exe Bob "is a jerk" helloworld.exe Bob“是一个混蛋”

Bob becomes the first parameter, since it has whitespace around it. Bob成为第一个参数,因为它周围有空格。 But "is a jerk" is all one because of the quotation marks. 但是“是一个混蛋”是因为引号所有。 So this would be two parameters. 所以这将是两个参数。

Your tags mention C, but I'm unclear if you actually meant you're calling this from C, the completely seperate language ; 你的标签提到C,但我不清楚你是否真的意味着你用C语言来称呼它,这是一种完全独立的语言 ; you seem to be just indicating you use a batch file. 你似乎只是在指示你使用批处理文件。

For your bat file, just add parameters after your exe path, like this: 对于你的bat文件,只需在exe路径后添加参数,如下所示:

pathname\helloworld\bin\debug\helloworld.exe param1 param2

Then, there's a method in your Program.cs file that looks like this: 然后,Program.cs文件中有一个方法如下:

[STAThread]
static void Main(string[] args)
{
  Application.Run(args.Length > 0 ? new Main(args[0]) : new Main());
}

Here you can tweak the parameters that are processed and send them to your startup form. 在这里,您可以调整处理的参数并将它们发送到启动表单。

As for the echo, that's just like a print statement, anything you want to output to the console window... 至于echo,就像print语句一样,你要输出到控制台窗口的任何东西......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM