问题描述
我正在使用以下代码,我从稍加修改。
I am using the following code that I obtained from here with some slight modifications.
public void ExecuteCommand(string WorkingDirectory, string command)
{
try
{
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd.exe", "/C " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.WorkingDirectory = WorkingDirectory ;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string Output = proc.StandardOutput.ReadToEnd();
string Errors = proc.StandardError.ReadToEnd();
}
catch (Exception objException)
{
// Log the exception
}
}
我用它来运行以下批处理文件:
I am using it to run the following batch file:
cd = "%~dp0"
(
vcvarsx86_amd64 & ifortvars
abaqus int j=SelfOptim_def user=feamac
abaqus int j=SelfOptim_forces user=feamac
abaqus SSpostfil_GNA
abaqus SSpostfil_GNB
)
如果我通过cmd定期运行批处理文件,则批处理文件可以正常运行。但是,如果我想通过C#运行该文件,它将无法正常运行。我使用的C#代码是否存在限制,我认为这不会导致此问题?有没有更好的办法?我到处寻找并尝试了各种方法来运行命令提示,但没有成功。
谢谢!
The batch file works perfectly if I run it regularly through cmd. However, if I want to run the file through C# it will not run correctly. Are there restrictions with the C# code that I am using that I don't see that are causing this? Is there a better way? I have looked everywhere and tried various methods to run the command prompt with no success.
Thanks!
推荐答案
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd.exe", "/C " + command);
//...
您只需要
You simply need
System.Diagnostics.Process.Start(command);
如果您需要重定向和其他选项,你只需要
If you need redirection and other options, you will simply need
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo(command);
//...
其中命令
可以是批处理文件的名称,甚至是系统注册表中注册的文档类型的文档。
where command
could be a name of you batch file, even a document of the document type registered in the system registry.
这篇关于命令提示符和批处理文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!