【问题标题】:C# under Linux, Process.Start() exception of "No such file or directory"Linux下C#,Process.Start()出现“No such file or directory”异常
【发布时间】:2018-10-01 21:26:40
【问题描述】:

我无法使用 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)

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

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

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

【问题讨论】:

  • 调用Process.Start时父进程的工作目录是什么?
  • 你有没有考虑过使用Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)来构建路径?
  • @FlorianWeimer @mjwills,父进程在/home/cli2/tmp/test/bin/Debug/netcoreapp2.1 开始,而我想要调用的程序在/home/cli2/tmp/program/lib。使用Path.GetDirectoryName(...) 为我提供了父进程路径。
  • 只是补充一下,我将FileName = ls 设置为WorkingDirectory = home/cli2/tmp/program/lib,我确实看到了我想调用的程序,但是当我将 FileName 更改为该程序时,它给了我没有这样的文件或目录错误。以及File.Exists("/home/cli2/tmp/program/lib/a.out") 返回true

标签: c# .net linux process


【解决方案1】:

我回答了你的other very similar question too,但这里有一个具体的答案。

忘记 WorkingDirectory,它不会指定新进程可执行文件的位置,除非你设置了UseShellExecute = trueHere is the documentation.

您必须在 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

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

=== 输出 ===

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!

【讨论】:

    猜你喜欢
    • 2016-01-05
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    相关资源
    最近更新 更多