C# 从MonoC运行Bash命令#

C# 从MonoC运行Bash命令#,c#,bash,shell,ubuntu,mono,C#,Bash,Shell,Ubuntu,Mono,我试图使用此代码创建一个目录,以查看代码是否正在执行,但由于某些原因,它执行时没有错误,但从未创建过目录。我的代码中有错误吗 var startInfo = new var startinfo = new ProcessStartInfo(); startinfo.WorkingDirectory = "/home"; proc.StartInfo.FileName = "/bin/bash"; proc.StartInfo.Arguments = "-c cd Desktop &

我试图使用此代码创建一个目录,以查看代码是否正在执行,但由于某些原因,它执行时没有错误,但从未创建过目录。我的代码中有错误吗

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()的工作目录的详细信息

此外,您的命令似乎错误,请使用
&&
执行多个命令:

  proc.StartInfo.Arguments = "-c cd Desktop && mkdir hey";
第三,您的工作目录设置错误:

 proc.StartInfo.WorkingDirectory = "/home";
这对我很有用:

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();
    }
}

什么是工作目录?我的解决方案存储在一个名为projects的文件夹中的thumb驱动器上,如果这是您的意思的话。我假设您最终真的在尝试做其他事情(而不是创建目录)。否则,似乎Directory.CreateDirectory(string)将是比使用shell更好的选择。桌面是否存在于/home目录下?如果是这样,为什么不将WorkingDirectory设置为“/home/Desktop”,只执行mkdir命令呢?我觉得这就是XY问题:我想执行保存在桌面上的shell脚本。您知道执行此命令的其他方法吗?由于某种原因,仍然存在问题。我将发布我现在使用的代码作为更新。谢谢,提供了一个已经包含返回输出的示例,对我帮助很大!我发现我需要使用
command=command.Replace(“\”,“\ \ \”)以使转义引号正常工作。除此之外,这是一个非常有用的答案。谢谢你善良的人类。