获取自包含EXE的路径?

Get self-contained EXE's path?

如果我们要部署 single file application,有没有办法从我们的代码中获取单个文件应用程序 .exe 的路径?

我问的原因是因为我有一个示例控制台应用程序,我想在注册表中注册它以在每次 windows 启动时启动,但遗憾的是每个已知的 API像 Assembly.GetExecutingAssembly().Location,或者 Microsoft AppContext.BaseDirectory return 相对于控制台应用程序的实际 .dll 文件建议的路径,而不是自包含的 .exe全部解压。

来自 GitHub issue,@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;
        }
    }
}