I have a directory which contains a self-contained "exe" and a config file. The exe has to read this config file. But the problem is that the exe can not get the right path of this config file.
Let me first talk about how I did it.
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);
}
}
}
How can I get the right path of this config file?
Take a look at this question: How can I get my .NET Core 3 single file app to find the appsettings.json file?
Self-contained .NET Core applications are automatically extracted into a temporary folder. So the path of the published executable is different from the path of the executed assembly.
That's way you have to use this: Path.GetDirectoryName(Process.GetCurrentProcess().MainModule)
With .NET 5, this became easier: now you can simply place appsettings.json
beside the EXE. By adding var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
the file will be read and the config can be accessed.
For other files, you can use AppDomain.CurrentDomain.BaseDirectory
.