【问题标题】:Passing arguments to a .cmd file in C#在 C# 中将参数传递给 .cmd 文件
【发布时间】:2020-05-29 02:52:10
【问题描述】:

我有一个 .cmd 文件,它要求用户输入,根据该输入执行进一步的步骤。我正在尝试编写一个程序来在 C# 中自动执行此过程,以便命令提示符在后台运行(不会弹出给用户/消除所有用户交互)并传递参数。我参考了多个答案,但没有找到解决方案。我已经参考了下面的链接。

Passing cmd line arguments to specific method

Passing Cmd Command to C# Application

Passing c# command line arguments in a batch file

如果有人能指出我正确的方向,那就太好了。

【问题讨论】:

  • 您正在寻找错误的东西。您需要寻找类似“c# 控制台重定向”的内容,例如stackoverflow.com/questions/21848271/… 这不是您需要的控制台应用程序参数,而是输入流。
  • 如果用户输入很简单,可以尝试在命令行中添加echo

标签: c# cmd


【解决方案1】:

1) 尝试编辑您的 bat/cmd 以接收 C# 中的参数:

  • args[]%1,%2,%n.../

2) 你需要编辑你的 bat/cmd 来接收你的 C# 参数:

  • Console.ReadLine()set /p some_var_by_input=/

    • 根据需要在 bat/cmd 文件中进行编辑:set / p input_1 =" Enter some entry: "

    • 删除并为您的论点添加适当的处理:

      set /p input_1="输入一些输入:"
      设置 input_1=%~1
    • 如果参数不止一个,就增加like...

      设置“input_2=%~2”
      设置“input_n=%~n”

这里是示例 代码将 2 个参数发送到 / 文件


using System;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    { 
        static void Main(string[] args)
        {
         System.Diagnostics.Process.Start(@"c:\batchfilename.bat", "\"1st\" \"2nd\"");
        }
    }
}

Obs.: 来自@T.S.Sathish answer here


  • 使用从 C# 传递的 %1 和 %2 参数的 bat 文件代码:
@echo off 
%__APPDIR__%mode.com con: cols=60 lines=6
echo/
echo/  your arg_CS[0] == arg_bat[%%1] == %1
echo/  your arg_CS[1] == arg_bat[%%2] == %2
echo/ ________________________________________________________
echo/ Please, press any key for me got to go drink a coffe...
@%__APPDIR__%timeout.exe -1 >nul


  • bat/cmd 输出:


选项 2:隐藏控制台窗口、传递参数并获取输出

using System;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    { 
        static void Main(string[] args)
        {
         var process = new Process();
         var startinfo = new ProcessStartInfo(@"c:\batchfilename.bat", "\"1st_arg\" \"2nd_arg\" \"3rd_arg\"");
         startinfo.RedirectStandardOutput = true;
         startinfo.UseShellExecute = false;
         process.StartInfo = startinfo;
         process.OutputDataReceived += (sender, argsx) => Console.WriteLine(argsx.Data); // do whatever processing you need to do in this handler
         process.Start();
         process.BeginOutputReadLine();
         process.WaitForExit();
        }
    }
}

这是基于我对英语的有限理解,如果不正确,抱歉,如果可能,请告诉我...


【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    相关资源
    最近更新 更多