c# - 如何获取 "SelfContained"和 "PublishSingleFile"exe的路径?

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

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

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

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

enter image description here

  • 添加代码
  • 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);
            }
        }
    }
    
  • 将此项目发布到“SelfContained”和“PublishSingleFile”exe
  • enter image description here

    enter image description here

  • 在exe所在目录添加文件“test.conf”
  • enter image description here

  • 运行此exe
  • enter image description here

    如何获得此配置文件的正确路径?

    最佳答案

    看看这个问题: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();将读取文件并可以访问配置。

    对于其他文件,您可以使用 AppDomain.CurrentDomain.BaseDirectory .

    关于c# - 如何获取 "SelfContained"和 "PublishSingleFile"exe的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64891586/

    相关文章:

    c# - 如何在 Azure C# SDK 中使用 WebAppsOperationsExtensions 和 IWebAppsOperations

    c# - 核心 API Controller 捕获所有未知路由

    c# - Wix - 如何在安装后从安装目录运行 exe 文件?

    用于 Swing 应用程序的 JAVA : SWING : How can i build a . exe

    c++ - 使用 NetBeans [C++] 制作安装程序

    c# - Asp.Net Core 2.x 中间件语法

    c# - C# 中接口(interface)成员的访问修饰符

    c# - NET CORE MVC - 如何使用嵌套的多参数化路由

    c# - 如何从 docusign 检索已签名的用户文档?

    c# - 使用来自 WCF 客户端的非 wcf SOAP 错误(已定义 soap 错误)