How can I get the application's path in a .NET console application?

后端 未结 27 2162
甜味超标
甜味超标 2020-11-21 11:11

How do I find the application\'s path in a console application?

In Windows Forms, I can use Application.StartupPath to find the current path, but this d

27条回答
  •  天命终不由人
    2020-11-21 12:01

    None of these methods work in special cases like using a symbolic link to the exe, they will return the location of the link not the actual exe.

    So can use QueryFullProcessImageName to get around that:

    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Diagnostics;
    
    internal static class NativeMethods
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern bool QueryFullProcessImageName([In]IntPtr hProcess, [In]int dwFlags, [Out]StringBuilder lpExeName, ref int lpdwSize);
    
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern IntPtr OpenProcess(
            UInt32 dwDesiredAccess,
            [MarshalAs(UnmanagedType.Bool)]
            Boolean bInheritHandle,
            Int32 dwProcessId
        );
    }
    
    public static class utils
    {
    
        private const UInt32 PROCESS_QUERY_INFORMATION = 0x400;
        private const UInt32 PROCESS_VM_READ = 0x010;
    
        public static string getfolder()
        {
            Int32 pid = Process.GetCurrentProcess().Id;
            int capacity = 2000;
            StringBuilder sb = new StringBuilder(capacity);
            IntPtr proc;
    
            if ((proc = NativeMethods.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid)) == IntPtr.Zero)
                return "";
    
            NativeMethods.QueryFullProcessImageName(proc, 0, sb, ref capacity);
    
            string fullPath = sb.ToString(0, capacity);
    
            return Path.GetDirectoryName(fullPath) + @"\";
        }
    }
    

提交回复
热议问题