繁体   English   中英

确定应用程序根目录的最佳方法是什么?

[英]What is the best way to determine application root directory?

我需要在我的应用程序根目录中获取所有dll。 最好的方法是什么?

string root = Application.StartupPath;

要么,

string root = new FileInfo(Assembly.GetExecutingAssembly().Location).FullName;

在那之后,

Directory.GetFiles(root, "*.dll");

哪种方式更好? 还有更好的方法吗?

AppDomain.CurrentDomain.BaseDirectory是我这样做的方式。

然而:

Application.StartupPath获取可执行文件的目录

AppDomain.BaseDirectory获取用于解析程序集的目录

由于它们可能不同,您可能希望使用Application.StartupPath,除非您关心程序集解析。

这取决于。 如果您想要启动应用程序的EXE目录,那么您的两个示例中的任何一个都可以使用。 但请记住,.NET非常灵活,可能是另一个应用程序链接到您的EXE并且正在调用它,可能来自另一个目录。

这种情况不会经常发生,如果有的话,你可能会写,但这是可能的。 因此,我更喜欢指定我感兴趣的程序集并从中获取目录。 然后我知道我将所有DLL都放在与特定程序集相同的目录中。 例如,如果您的应用程序MyApp.exe中有一个类MyApp.MyClass,那么您可以这样做;

string root = string.Empty;
Assembly ass = Assembly.GetAssembly( typeof( MyApp.MyClass ) );
if ( ass != null )
{
   root = ass.Location;
}

这是一个老问题,但我总是习惯使用:

Environment.CurrentDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

但是,看看这里的解决方案,我认为需要做一些简单的测试:

var r = new List<long>();
var s = Stopwatch.StartNew();

s.Restart();
string root1 = Application.StartupPath;
r.Add(s.ElapsedTicks);

s.Restart();
string root2 = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
r.Add(s.ElapsedTicks);

s.Restart();
string root3 = Path.GetDirectoryName(new FileInfo(Assembly.GetExecutingAssembly().Location).FullName);
r.Add(s.ElapsedTicks);

s.Restart();
string root4 = AppDomain.CurrentDomain.BaseDirectory;
r.Add(s.ElapsedTicks);

s.Restart();
string root5 = Path.GetDirectoryName(Assembly.GetAssembly( typeof( Form1 ) ).Location);
r.Add(s.ElapsedTicks);

滴答结果如下:

  • 49
  • 306
  • 166
  • 26
  • 201

所以似乎AppDomain.CurrentDomain.BaseDirectory是要走的路。

如果要获取应用程序根文件夹路径,请使用下面的代码示例。

string path =new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName

我用

Path.GetDirectoryName(new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath)

如果使用卷影复制,Assembly.Location将指向卷影副本,因此使用CodeBase是更好的选择,但CodeBase是一个Url。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM