[英]Running string as a Batch file in c#
我正在编写一个创建批处理文件然后运行的应用程序:
我知道我可以创建一个批处理文件并运行该文件。
我想做的是:一旦创建了构成文件的字符串,是否有任何方法可以将字符串作为批处理文件执行? 就像是
string BatchFile = "echo \"bla bla\" \n iperf -c 123 ... ... .. "
Diagnostics.Process.Start(BatchFile);
您可以使用/ c作为可执行文件来运行CMD.EXE ,并将其余部分作为参数:
Process.Start("cmd.exe", "/c echo \"bla bla\" \n iperf -c 123 ... ... .. ");
对我来说,我正在使用以下代码:
Process process;
private void button1_Click(object sender, EventArgs e)
{
process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "cmd";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.Start();
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
process.StandardInput.WriteLine("cd d:/tempo" );
process.StandardInput.WriteLine("dir");
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
string line;
while (!process.StandardOutput.EndOfStream)
{
line = process.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{
SetText(line);
}
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text += text + Environment.NewLine;
}
}
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
process.StandardInput.WriteLine("exit");
process.Close();
}
您可以将您的批处理“文件”创建为长字符串,并以\\n
终止行,这与您在示例中显示的完全相同,然后执行cmd.exe并执行该字符串重定向(我称其为“ NotBatch-text”),并重定向串入其Stdin标准手柄。 这样,您的“ NotBatch文本”可能会使用大量的批处理功能,例如%variables%的扩展,嵌套在任何级别的IF
和FOR
命令等等。 您还可以使用延迟!变量! 如果使用/V:ON
开关执行cmd.exe,则扩展。 实际上,在NotBatch文本中唯一不起作用的是:参数和SHIFT
命令以及GOTO
/ CALL :label
命令; 在这个职位的进一步细节。
如果要执行更高级的“NotBatch文本”的字符串,你甚至可以模拟 GOTO
和CALL :label
与第三方程序的帮助下命令,如在描述这个职位 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.