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

后端 未结 27 2051
甜味超标
甜味超标 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 11:47

    Assembly.GetEntryAssembly().Location or Assembly.GetExecutingAssembly().Location

    Use in combination with System.IO.Path.GetDirectoryName() to get only the directory.

    The paths from GetEntryAssembly() and GetExecutingAssembly() can be different, even though for most cases the directory will be the same.

    With GetEntryAssembly() you have to be aware that this can return null if the entry module is unmanaged (ie C++ or VB6 executable). In those cases it is possible to use GetModuleFileName from the Win32 API:

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
    

提交回复
热议问题