如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
如何在控制台应用程序中找到应用程序的路径?
在Windows窗体中,我可以使用应用程序。StartupPath来查找当前路径,但这在控制台应用程序中似乎不可用。
当前回答
为什么不是p/invoke方法呢?
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());
}
}
}
您可以像使用应用程序一样使用它。StartupPath:
Console.WriteLine("The path to this executable is: " + AppInfo.StartupPath + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");
其他回答
Assembly.GetEntryAssembly()。Location或Assembly.GetExecutingAssembly().Location
与System.IO.Path.GetDirectoryName()结合使用只获取目录。
来自GetEntryAssembly()和GetExecutingAssembly()的路径可以不同,即使在大多数情况下目录是相同的。
使用GetEntryAssembly(),你必须意识到,如果入口模块是非托管的(即c++或VB6可执行文件),它可能返回null。在这些情况下,可以使用Win32 API中的GetModuleFileName:
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
在VB.net
My.Application.Info.DirectoryPath
工作为我(应用类型:类库)。不太懂c#… 返回文件名为字符串的路径
AppDomain.CurrentDomain.BaseDirectory
将解决问题,以引用第三方参考文件与安装包。
.Location1 System.Reflection.Assembly.GetExecutingAssembly ()
如果你想要的只是目录,将它与System.IO.Path.GetDirectoryName结合起来。
根据minor先生的评论: System.Reflection.Assembly.GetExecutingAssembly()。Location返回正在执行的程序集当前所在的位置,该位置可能是也可能不是程序集未执行时所在的位置。在阴影复制程序集的情况下,您将获得临时目录中的路径。System.Reflection.Assembly.GetExecutingAssembly()。CodeBase将返回程序集的“永久”路径。
你可能会这样做:
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)