简体   繁体   中英

I get a can't execute binary file error when running a bash command from C#

I've created a Discord Bot with which you can interact (running on a Raspberry Pi with a default Raspberry Pi OS). I also added a command to execute a shell command. My code:

        ProcessStartInfo inf = new()
        {
              CreateNoWindow = true,
              RedirectStandardError = true,
              RedirectStandardOutput = true,
              RedirectStandardInput = true,
              FileName = "/bin/bash",
              Arguments = command,
        };
        if (Process.Start(inf) is Process cmd)
        {
                string ret = "Output: " + await cmd.StandardOutput.ReadToEndAsync();
                ret += "\nError Output: " + await cmd.StandardError.ReadToEndAsync();
                await Program.Log(ret);
                return ret;
        }

When I set command to "echo Hello, World!" I just get the error

/usr/bin/echo: /usr/bin/echo: cannot execute binary file

from the StandardOutput. What am I doing wrong?

You have to pass -c parameter to bash if you want execute something through it

ProcessStartInfo inf = new()
{
   CreateNoWindow = true,
   RedirectStandardError = true,
   RedirectStandardOutput = true,
   RedirectStandardInput = true,
   FileName = "/bin/bash",
   Arguments = $"-c \"{command}\""
};
if (Process.Start(inf) is Process cmd)
{
   string ret = "Output: " + await cmd.StandardOutput.ReadToEndAsync();
   ret += "\nError Output: " + await cmd.StandardError.ReadToEndAsync();
   await Program.Log(ret);
   return ret;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM