【问题标题】:Run a c# Console App with .application file type from a .BAT从 .BAT 运行具有 .application 文件类型的 c# 控制台应用程序
【发布时间】:2011-09-10 14:47:46
【问题描述】:

我创建了一个可以读取命令参数的控制台应用程序(使用 Visual Studio 2010)。

调试时,我会解析一些在 Project-> [project name] Properties... -> Debug -> Command line arguments 中设置的测试参数:

上面写着: "参数名1|参数值1" "参数名2|参数值2" "参数名3|参数值3"

我使用以下代码读取参数:

for (Int16 argumentsCount = 0; argumentsCount < args.Length; argumentsCount++)
{
    String[] parameterItem = args[argumentsCount].Split('|');
    String parameterName = parameterItem[0].ToString();
    String parameterValue = parameterItem[1].ToString();
    /*code continues*/

}

当我在调试模式下运行应用程序时,它运行良好并且所有参数都被读取。

然后我将应用程序发布到服务器并确保它以正确的权限安装(为了演示的目的,假设它位于 C:\MyApp 上,编译后的代码位于 MyApp.application 中

然后我创建了一个执行应用程序的批处理脚本。 *.BAT 包含以下命令:

"C:\MyApp\MyApp.application" "parametername1|parametervalue1" "parametername2|parametervalue2" "parametername3|parametervalue3"

当我运行批处理时,当应用程序执行时,这种工作方式......但是......我的应用程序没有接收到我的参数。我知道这一点是因为我重新编译并发布了一些代码,以读取接收到的参数数量:

Console.Write("Arguments " + args.Length.ToString());

这显示参数:0

谁能告诉我如何编写批处理脚本来运行应用程序并解析我的参数/命令行参数。

【问题讨论】:

  • /astandard wayofdoingit?

标签: c# console batch-file console-application command-line-arguments


【解决方案1】:

预计到达时间:没关系。你的问题是.application 而不是.exe。在您的文件关联中查看 .application.exe 相比会发生什么:

> assoc .application
.application=Application.Manifest

> ftype Application.Manifest
Application.Manifest=rundll32.exe dfshim.dll,ShOpenVerbApplication %1

> assoc .exe
.exe=exefile

> ftype exefile
exefile="%1" %*

您看到那里传递的内容有什么不同吗?即普通可执行文件获取命令行参数(%*)。所以我想你应该使用可执行文件而不是可执行文件清单或 .application 实际上是什么(老实说,我从未在野外见过它)。


使用相当少的测试程序

class Args {
    static void Main(string[] args) {
        for (int i = 0; i < args.Length; i++) {
            System.Console.WriteLine("[{0}]=<{1}>", i, args[i]);
        }
    }
}

它对我来说很好用。以下批处理文件:

@"args.exe" "parametername1|parametervalue1" "parametername2|parametervalue2" "parametername3|parametervalue3"

产生以下输出:

[0]=<parametername1|parametervalue1>
[1]=<parametername2|parametervalue2>
[2]=<parametername3|parametervalue3>

所以我猜你没有向我们展示的代码有问题。也许您实际上并没有在 C# 应用程序中使用命令行参数,而是在那里引用了不同的 string[]

【讨论】:

  • 非常感谢大家。我的问题确实是我正在执行 .application 文件。要获取 .exe,我只需进入项目 bin/Debug 目录并将 .exe 复制到我的部署目录。然后我修改了我的批处理脚本来执行.exe,当我再次运行我的批处理脚本时......嘿,presto,它工作了!所以我的批处理脚本最后看起来像这样: "C:\MyApp\MyApp.exe" "parametername1|parametervalue1" "parametername2|parametervalue2" "parametername3|parametervalue3"
【解决方案2】:

管道字符| 在批处理文件中具有特殊含义。我建议使用不同的字符来使事情变得更容易。否则,您必须使用 Escape Character 才能使用管道字符。它可能看起来像这样:

"C:\MyApp\MyApp.application" "parametername1^|parametervalue1" "parametername2^|parametervalue2" "parametername3^|parametervalue3"

注意管道|之前的插入符号^

【讨论】:

  • 您好,感谢您的回复。我尝试使用“^”字符,但它似乎仍然不起作用。我的批处理脚本和解析参数的方式一定有问题……我只是想不通。有人吗?
  • | 不是问题,因为他们正确地引用了它。它被正确地传递给应用程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 2011-01-22
  • 1970-01-01
  • 2014-12-27
相关资源
最近更新 更多