[英]Run Bash Commands from Mono C#
我正在嘗試使用此代碼創建目錄,以查看代碼是否正在執行,但由於某種原因,它執行時沒有錯誤,但從未創建目錄。 我的代碼中是否存在錯誤?
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();
這對我有用:
Process.Start("/bin/bash", "-c \"echo 'Hello World!'\"");
這對我最有效,因為現在我不必擔心轉義引號等問題。
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();
}
}
我的猜測是您的工作目錄不在您期望的位置。
請參閱此處以獲取有關Process.Start()
工作目錄的更多信息。
同樣您的命令似乎有誤,請使用&&
執行多個命令:
proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";
第三,您錯誤地設置了工作目錄:
proc.StartInfo.WorkingDirectory = "/home";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.