C# c“如何获得a的路径”;自足的;及;PublishSingleFile“;exe?

C# c“如何获得a的路径”;自足的;及;PublishSingleFile“;exe?,c#,exe,self-contained,.net-core-publishsinglefile,C#,Exe,Self Contained,.net Core Publishsinglefile,我有一个目录,其中包含一个自包含的“exe”和一个配置文件。exe必须读取此配置文件。但问题是exe无法获取此配置文件的正确路径 让我先谈谈我是怎么做到的 1、在VS2019中创建一个NET5.0项目 2、添加代码 using System; using System.IO; using System.Reflection; namespace TestFile { class Program { static void Main(string[] args) {

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

让我先谈谈我是怎么做到的

1、在VS2019中创建一个NET5.0项目

2、添加代码

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);
        }
    }
}
3、将此项目发布到“自包含”和“PublishSingleFile”exe

4,在exe所在的目录中添加文件“test.conf”

5,运行这个exe


如何获取此配置文件的正确路径?请帮忙!谢谢。

看看这个问题:

.NET核心3.1 自包含的.NET核心应用程序会自动提取到临时文件夹中。因此,发布的可执行文件的路径与实际执行的程序集的路径不同

这就是您必须使用的方法:
Path.GetDirectoryName(Process.GetCurrentProcess().MainModule)

.NET 5
使用.NET5,这变得更容易:现在您只需将
appsettings.json
放在EXE旁边即可。通过添加
var config=new ConfigurationBuilder().AddJsonFile(“appsettings.json”).Build()
将读取文件并访问配置。

尝试使用Build Action=Content和Copy to Output Directory=alway标记
test.conf
,另一个选项是将
test.conf
的路径作为命令行参数传递,并在
Main()
这两个选项中提取它。还有其他方法吗?请描述一下这两个选项不起作用的地方吗?也许可以尝试以下方法:请注意,除非您使用includealContentForSelfExtract标志,该标志将行为还原为.NET Core 3样式的self,否则这在.NET 5上不再起作用contained@Mgamerz我已经更新了我的答案。