问题
I have a .cmd file which asks the user for an input, based on which further steps are performed. I am trying to write a program to automate this process in C# such that command prompt runs in the background(without popping up to the user/eliminating all user interaction) and the arguments get passed. I have referred to multiple answers, however did not find a solution. I have already referred the links below.
Passing cmd line arguments to specific method
Passing Cmd Command to C# Application
Passing c# command line arguments in a batch file
It would be great if anyone could point me in the right direction.
回答1:
1) Try edit your bat/cmd for receive arguments thought in C#:
args[]in c# is%1,%2,%n...in bat/cmd
2) You need edit your bat/cmd to receive your C# arguments:
Console.ReadLine()in c# isset /p some_var_by_input=in bat/cmdEdit in the bat/cmd file, wherever you need:
set / p input_1 =" Enter some entry: "Remove and add the appropriate treatment to your arguments:
set /p input_1="Enter some input:"set input_1=%~1If there is more than one argument, just increase like...
set "input_2=%~2" set "input_n=%~n"
Here is sample c# code that are sending 2 arguments to a bat/cmd file
using System;
using System.Diagnostics;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Process.Start(@"c:\batchfilename.bat", "\"1st\" \"2nd\"");
}
}
}
Obs.: c# sources from @T.S.Sathish answer here
- The bat file code using %1 & %2 arguments passed from C #:
@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 outputs:
Option 2 : Hiding the console window, passing arguments and taking outputs
- This is an edit from this answer /by @Brian Rasmussen
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();
}
}
}
This is based on my limited understanding of English so if that is not correct, sorry, and if possible, please let me know ...
来源:https://stackoverflow.com/questions/60207122/passing-arguments-to-a-cmd-file-in-c-sharp