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

后端 未结 27 1456
甜味超标
甜味超标 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:02

    I mean, why not a p/invoke method?

        using System;
        using System.IO;
        using System.Runtime.InteropServices;
        using System.Text;
        public class AppInfo
        {
                [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
                private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
                private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
                public static string StartupPath
                {
                    get
                    {
                        StringBuilder stringBuilder = new StringBuilder(260);
                        GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
                        return Path.GetDirectoryName(stringBuilder.ToString());
                    }
                }
        }
    

    You would use it just like the Application.StartupPath:

        Console.WriteLine("The path to this executable is: " + AppInfo.StartupPath + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");
    

提交回复
热议问题