Shell Script File(.Sh) Does Not Run from C# Core on Linux

C# under Linux, Process.Start() exception of No such file or directory

I answered your other very similar question too, but here is a specific answer to this one.

Forget about WorkingDirectory, it does not specify the location of the new process executable unless you set UseShellExecute = true. Here is the documentation.

You have to use a relative path to the project root in FileName. Like this: process.StartInfo.FileName="bin/wrapper.sh";

I don't know of a way to execute a file and set that process' working directory on Linux from within dotnet core and C#.

What you could do is create a wrapper script to execute your file in lib.

Under our project root we have two files. Be sure both have chmod +x.

  • bin/wrapper.sh - this file will execute lib/a.out
  • lib/a.out - Hello, World!

bin/wrapper.sh

#!/bin/bash

cd lib
pwd
./a.out

Program.cs

using System;
using System.Diagnostics;

namespace SO_Question_52599105
{
class Program
{
static void Main(string[] args)
{
Process process = new Process();
process.StartInfo.FileName="bin/wrapper.sh";
process.Start();
}
}
}

=== OUTPUT ===

larntz@dido:/home/larntz/SO_Question_52599105$ ls
bin hello.c lib obj Program.cs SO_Question_52613775.csproj

larntz@dido:/home/larntz/SO_Question_52599105$ ls bin/
Debug wrapper.sh

larntz@dido:/home/larntz/SO_Question_52599105$ ls lib/
a.out

larntz@dido:/home/larntz/SO_Question_52599105$ dotnet run
/home/larntz/SO_Question_52599105/lib
Hello, World!

Exectute a Linux Shell command from ASP.NET Core 3 app

Assume you want to run echo hello in bash, then

    Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "bash",
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
}
};
process.Start();
await process.StandardInput.WriteLineAsync("echo hello");
var output = await process.StandardOutput.ReadLineAsync();
Console.WriteLine(output);


Related Topics



Leave a reply



Submit