If we're deploying a single file application, is there a way to get the single file application .exe
's path from inside our code?
The reason I'm asking is because I have a sample console application, which I'd like to register in the registry to start every time windows starts, but sadly every known API like Assembly.GetExecutingAssembly().Location
, or the one suggested by Microsoft AppContext.BaseDirectory
return paths relative to the actual .dll
file of the console application, not the self-contained .exe
which unpackages it all.
From GitHub issue, suggestion by @Symbai:
public static class Extensions {
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern uint GetModuleFileName(IntPtr hModule, System.Text.StringBuilder lpFilename, int nSize);
static readonly int MAX_PATH = 255;
public static string GetExecutablePath() {
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) {
var sb = new System.Text.StringBuilder(MAX_PATH);
GetModuleFileName(IntPtr.Zero, sb, MAX_PATH);
return sb.ToString();
}
else {
return System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
}
}
}