Linux 下的 C#,Process.Start() 异常“没有这样的文件或目录”

cli*_*li2 9 .net c# linux process

我无法使用 Process 类调用程序来启动程序。可执行文件的层次结构在 bin 目录下,而当前工作目录需要在 lib 目录下。

/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)
Run Code Online (Sandbox Code Playgroud)

我已经设置了WorkingDirectory = "path/lib""FileName = "../bin/a.out"。但是我收到一个错误:

Unhandled Exception: System.ComponentModel.Win32Exception: No such file or directory
Run Code Online (Sandbox Code Playgroud)

我尝试设置WorkingDirectory为绝对和相对路径,但都不起作用。我已经编写了一个 bash 脚本来从 lib 目录执行 a.out,并使用我调用 bash 脚本的 Process 类,这是可行的,但我想在没有 bash 脚本解决方法的情况下执行此操作。那么如何解决这个路径问题呢?

LAr*_*ntz 5

我也回答了你的另一个非常相似的问题,但这里有一个具体的答案。

忘记 WorkingDirectory,它不会指定新进程可执行文件的位置,除非您设置UseShellExecute = true. 这是文档

您必须在 FileName 中使用项目根目录的相对路径。像这样:process.StartInfo.FileName="bin/wrapper.sh";

我不知道有什么方法可以从 dotnet core 和 C# 中执行文件并在 Linux 上设置该进程的工作目录。

您可以做的是创建一个包装脚本来在 lib 中执行您的文件。

在我们的项目根目录下,我们有两个文件。确保两者都有chmod +x

  • bin/wrapper.sh - 该文件将执行 lib/a.out
  • lib/a.out - 你好,世界!

bin/wrapper.sh

#!/bin/bash

cd lib
pwd
./a.out
Run Code Online (Sandbox Code Playgroud)

程序.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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

=== 输出 ===

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!
Run Code Online (Sandbox Code Playgroud)