如何在C#中运行bat文件?我无法运行它. [英] How to run a bat file in C#? I am unable to run it.

查看:291
本文介绍了如何在C#中运行bat文件?我无法运行它.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码确实等待bat运行:

This code does wait for bat to run:

System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
psi.WorkingDirectory = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
psi.WorkingDirectory = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + @"\Web\SNIF\Graph";
// Start the process
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
//System.Diagnostics.Process  proc = new System.Diagnostics.Process();

// Open the batch file for reading
System.IO.StreamReader strm = System.IO.File.OpenText(batFilePath);
// proc.Start();
// proc.WaitForExit();
// Attach the output for reading
System.IO.StreamReader sOut = proc.StandardOutput;
// Attach the in for writing
System.IO.StreamWriter sIn = proc.StandardInput;

string sText = "";

while (strm.Peek() != -1)
{
    sText = strm.ReadLine();
    sIn.WriteLine(sText);
}
proc.WaitForExit();
sIn.WriteLine("EXIT");
strm.Close();
string stEchoFmt = "# {0} run successfully. Exiting";
//sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
sIn.WriteLine("EXIT");
proc.Close();
// Read the sOut to a string.
string results = sOut.ReadToEnd().Trim();
// Close the io Streams;
sIn.Close();
sOut.Close();


proc.WaitForExit();挂起.为什么?

[需要添加代码块]


proc.WaitForExit(); hangs on. Why?

[Code block required and added]

推荐答案

要添加到Toli的答案中,在批处理文件的末尾?这将导致批处理文件在继续输入之前等待输入(从而防止cmd.exe退出).
To add to Toli''s answer, do you have a pause statement at the end of your batch file? That will cause the batch file to wait for input before proceeding (thus preventing cmd.exe from exiting).


我最近测试了从一个程序运行批处理文件,使用Process.Start(),针对其他问题.如果您直接使用批处理文件名,它将起作用:
I recently tested running batch file from a program using Process.Start(), in response to other Question. It does work if you use your batch file name directly:
System.Diagnostics.Process.Start("MyCommands.bat", "my command line parameters");



确保使用正确目录(例如,可执行文件)中的文件.您永远不要假定工作目录,这取决于您运行应用程序的方式(可以从任何目录运行它).要查找您的可执行目录,请使用以下命令:



Make sure you use the file in right (for example, your executable) directory. You should never assume working directory, it depends on how you run your application (you can run it from any directory). To find out your executable directory, use this:

string exeDir = System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetEntryAssembly().Location);



—SA



—SA


可能是因为cmd没有退出.


这篇关于如何在C#中运行bat文件?我无法运行它.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆