【问题标题】:How to get the path of a "SelfContained" and "PublishSingleFile" exe?如何获取“SelfContained”和“PublishSingleFile”exe 的路径?
【发布时间】:2021-03-01 15:11:36
【问题描述】:

我有一个目录,其中包含一个独立的“exe”和一个配置文件。 exe 必须读取此配置文件。但问题是exe无法获取此配置文件的正确路径。

我先说一下我是怎么做到的。

  1. 在VS2019中创建NET5.0项目

  1. 添加代码
using System;
using System.IO;
using System.Reflection;

namespace TestFile {
    class Program {
        static void Main(string[] args) {
            string assemblyLocation = Assembly.GetEntryAssembly().Location;
            Console.WriteLine($"assemblyLocation=\"{assemblyLocation}\"");
            string configFile = Path.Combine((new FileInfo(assemblyLocation)).DirectoryName, "test.conf");
            Console.WriteLine($"configFile=\"{configFile}\"");
            File.ReadAllText(configFile);
        }
    }
}
  1. 将此项目发布到“SelfContained”和“PublishSingleFile”exe 中

  1. 在exe所在目录添加文件“test.conf”

  1. 运行这个 exe

我怎样才能得到这个配置文件的正确路径?

【问题讨论】:

  • 尝试用 Build Action = ContentCopy to Output Directory = Always 标记test.conf
  • 其他选项是将路径传递给test.conf 作为命令行参数并在Main() 中提取它
  • 这两个选项都不是。还有其他方法吗?
  • 能否请您描述一下这两个选项不适用的地方?

标签: c# .net-core exe .net-core-publishsinglefile


【解决方案1】:

看看这个问题:How can I get my .NET Core 3 single file app to find the appsettings.json file?

.NET Core 3.1

自包含的 .NET Core 应用程序会自动提取到一个临时文件夹中。所以发布的可执行文件的路径与实际执行的程序集的路径不同。

这就是你必须使用它的方式:Path.GetDirectoryName(Process.GetCurrentProcess().MainModule)

.NET 5

使用 .NET 5,这变得更容易:现在您可以简单地将 appsettings.json 放在 EXE 旁边。通过添加var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); 将读取文件并可以访问配置。

【讨论】:

  • 请注意,这不再适用于 .NET 5,除非您使用 IncludeAllContentForSelfExtract 标志,它将行为恢复为 .NET Core 3 的自包含样式
【解决方案2】:

我读过推荐的方法是Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName),但是这对我来说返回了 null (.NET 6)。我怀疑这是因为代码在另一个项目的 DLL 中。在这两种情况下,一个更强大的方法似乎是AppContext.BaseDirectory。 .NET 使用它来搜索程序集依赖项,并将指向基本应用程序目录。很容易记住,并且会立即为您提供目录而不是文件名!

【讨论】:

    猜你喜欢
    • 2011-01-16
    • 2019-07-10
    • 2021-07-21
    • 2020-06-02
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    相关资源
    最近更新 更多