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

社会主义新天地 提交于 2021-02-20 06:12:11

问题


I am having trouble calling a program with the Process class to start a program. The hierarchy to the executable is in under the bin directory while the current working directory needs to be under the lib directory.

/project
    /bin
        a.out (this is what I need to call)
    /lib
        (this is where I need to be in order for a.out to work)

I have set the WorkingDirectory = "path/lib" and the "FileName = "../bin/a.out". However I am getting an error of:

Unhandled Exception: System.ComponentModel.Win32Exception: No such file or directory

I tried setting WorkingDirectory to absolute and relative path, but neither works. I have written a bash script to executes a.out from the lib directory, and using the Process class I call the bash script, this works but I want to do this without the bash script workaround. So how do I resolve this pathing issue?


回答1:


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!


来源:https://stackoverflow.com/questions/52599105/c-sharp-under-linux-process-start-exception-of-no-such-file-or-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!