我正在尝试使用此代码创建一个目录,以查看代码是否正在执行但由于某种原因它执行时没有错误但是目录永远不会生成。我的代码在某处有错误吗?
var startInfo = new
var startinfo = new ProcessStartInfo();
startinfo.WorkingDirectory = "/home";
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();
Console.WriteLine ("Shell has been executed!");
Console.ReadLine();
答案 0 :(得分:3)
这对我来说效果最好,因为现在我不必担心转义引号等...
using System;
using System.Diagnostics;
class HelloWorld
{
static void Main()
{
// lets say we want to run this command:
// t=$(echo 'this is a test'); echo "$t" | grep -o 'is a'
var output = ExecuteBashCommand("t=$(echo 'this is a test'); echo \"$t\" | grep -o 'is a'");
// output the result
Console.WriteLine(output);
}
static string ExecuteBashCommand(string command)
{
// according to: https://stackoverflow.com/a/15262019/637142
// thans to this we will pass everything as one command
command = command.Replace("\"","\"\"");
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = "-c \""+ command + "\"",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
proc.WaitForExit();
return proc.StandardOutput.ReadToEnd();
}
}
答案 1 :(得分:2)
这对我有用:
Process.Start("/bin/bash", "-c \"echo 'Hello World!'\"");
答案 2 :(得分:0)
我的猜测是你的工作目录不在你预期的位置。
See here了解有关Process.Start()
你的命令似乎也错了,用&&
执行多个命令:
proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";
第三,你错误地设置你的工作目录:
proc.StartInfo.WorkingDirectory = "/home";