我正在尝试从 C# 调用 .bat 文件。 我的项目名称是 这是代码 MaestroStart,批处理文件具有相同的名称。它们都在同一目录中。
private void button1_Click(object sender, EventArgs e)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = @"C:\Program Files (x86)\mbmteks\Maestro\MaestroStart.bat";
p.StartInfo.WorkingDirectory = @"C:\Program Files (x86)\mbmteks\Maestro\MaestroStart\MaestroStart\bin\Debug";
p.Start();
//string output = p.StandardError.ReadToEnd();
string output = p.StandardOutput.ReadToEnd();
textBox2.Text = output;
p.WaitForExit();
}
但这是我得到的唯一输出: (“JAVA_HOME 不指向 JDK 或 JRE。请设置 JAVA_HOME 环境变量或为您的 IDEA 项目指定 JDK。”)。 如果使用这个语句
string output = p.StandardError.ReadToEnd();
屏幕上什么也没显示。
我尝试将 Jave-Home 环境变量重置为我正在使用的所有目录,但没有任何变化。
这是批处理文件的代码:
@echo off
setlocal
Set JAVA_HOME=.\jre
if exist "%JAVA_HOME%\bin\java.exe" goto JavaFound
echo "JAVA_HOME does not point at a JDK or JRE. Either set the JAVA_HOME environment variable or specify a JDK for your IDEA project."
goto End
:JavaFound
if exist "start.jar" goto StartJarFound
echo "start.jar was not found. Check your Jetty installation or your app path."
goto End
:StartJarFound
%JAVA_HOME%\bin\java.exe -jar start.jar
:End
这是我直接运行批处理文件时的输出:
警告:系统属性和/或 JVM 参数已设置。考虑使用 --dry-run 或 --e 埃克 2014-03-11 13:35:51.964:信息:oejs.服务器:jetty-8.1.12.v20130726 2014-03-11 13:35:51.998:INFO:oejdp.ScanningAppProvider:部署监视器 C:\Pro gram 文件 (x86)\mbmteks\Maestro\webapps,间隔为 1 2014-03-11 13:35:52.010:INFO:oejd.DeploymentManager:可部署添加:C:\Program 文件 (x86)\mbmteks\Maestro\webapps\ROOT log4j:WARN org.apache.log4j.DailyRollingFileAp 中没有这样的属性 [maxFileSize] 彭德。 log4j:WARN org.apache.log4j.DailyRollingFil 中没有这样的属性 [maxBackupIndex] eAppender。 2014-03-11 13:36:00.540:INFO:ROOT:初始化 Spring 根 WebApplicationContext
2014-03-11 13:36:03.274:INFO:ROOT:初始化 Spring FrameworkServlet 'springDi 喷射器' 2014-03-11 13:36:03.647:INFO:oejdp.ScanningAppProvider:部署监视器 C:\Pro gram 文件 (x86)\mbmteks\Maestro\contexts,间隔为 1 2014-03-11 13:36:03.671:INFO:oejs.AbstractConnector:开始 SelectChannelConnect 或@0.0.0.0:9999
我的工作目录正确吗?我的意思是,它应该是我当前项目的目录??
最佳答案
//to excute bat file in java
Runtime runtime = Runtime.getRuntime();
try {
Process p1 = runtime.exec("cmd /c GO.BAT", null, new File("D:\\Documents and Settings\\Administrator\\Desktop\\bat"));
InputStream is = p1.getInputStream();
int i = 0;
while( (i = is.read() ) != -1) {
System.out.print((char)i);
}
} catch(IOException ioException) {
System.out.println(ioException.getMessage() );
}
关于c# - 当我在 C# 中执行 .bat 文件时无法获得输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22320351/