我试图在我的程序背景下的cmd中运行这些命令:
我不知道该从哪里开始,但我试过这样做:
private void FileSelect_Click(object sender, EventArgs e)
{
string databaseDirectory = saveAndLoad.getFolderContentsFilename();
FilePath.Text = databaseDirectory;
}
private void xmlGenerator_Click(object sender, EventArgs e)
{
string file = FilePath.ToString();
var process = new Process();
var startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "path to your script file..."
};
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
if (process.ExitCode == 0)
{
//success
}
else
{
//an error occured during script execution...
}
}我的代码的总体目标是根据提交给SVN的更改生成一个xml文件,需要运行的命令行应该创建一个xml文件。我想在没有显示cmd的情况下在程序的背景中这样做。
任何帮助都会很好。
谢谢
发布于 2015-09-22 10:41:42
您正在尝试运行位于startInfo.FileName路径的文件中的程序,而不是脚本。将要执行的脚本保存到文件中,将脚本文件的路径传递给StartInfo对象,启动进程并等待其执行:
var process = new Process();
var startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "path to your script file..."
};
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
if (process.ExitCode == 0)
{
//success
}
else
{
//an error occured during script execution...
}发布于 2015-09-22 10:41:49
对于任何命令,我都使用以下函数,它总是有效的:这里需要传递两个参数。1)你的命令和2)你的目录。
private string BatchCommand(string cmd, string mapD)
{
Batchresults = "";
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmd);
procStartInfo.WorkingDirectory = mapD;
// 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.RedirectStandardInput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process cmdProcess = new System.Diagnostics.Process();
cmdProcess.StartInfo = procStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit.
cmdProcess.WaitForExit();
// Get the output into a string
return Batchresults;
}
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
Batchresults += Environment.NewLine + e.Data.ToString();
}
void cmd_Error(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
Batchresults += Environment.NewLine + e.Data.ToString();
}
}注意,Batchresults是一个全局字符串。
调用脚本为
string result= BatchCommand("Your command here","Directory from where you want to execute it");字符串结果将包含所有结果和错误的详细信息。
https://stackoverflow.com/questions/32714551
复制相似问题