咨询区
- JSmyth:
如何在 Console 程序中找到应用程序的路径?
在 Windows Form
中,我可以通过 Application.StartupPath
找到应用程序的当前路径,但在 Console 中这样写是报错的。
回答区
- F.Alves:
对于 Console 应用程序,你可以这么试一下。
System.IO.Directory.GetCurrentDirectory();
输出 (我的电脑):
c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug
或者用下面这种方式。
AppDomain.CurrentDomain.BaseDirectory
输出:
c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug\
- user2126375:
下面代码可以获取应用程序的路径。
var applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)
这种 获取法
合适下面的一些场景。
- 简单的应用程序。
- 在另一个 domain 中使用
Assembly.GetEntryAssembly()
返回为null的情况。 - dll作为bytes形式的内嵌资源并通过
Assembly.Load(byteArrayOfEmbeddedDll)
加载到 AppDomain。 - Mono 的
mkbundle
中。
- user3596865:
我在想为什么不使用 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());
}
}
}
然后使用 Application.StartupPath
就能获取当前程序的路径了。
- Steve Mc:
你有三种选择获取 应用程序
的路径,具体选择哪一个取决于你的场景。
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
string path = Environment.GetCommandLineArgs()[0];
点评区
一个非常简单的问题,万万没想到居然能罗列 7种 写法,学习了