[英]AppDomain.CurrentDomain.BaseDirectory changes to wrong directory
[英]Should I use AppDomain.CurrentDomain.BaseDirectory or System.Environment.CurrentDirectory?
我在同一个文件夹中有两个 exe 文件,我可以从 exe1 中的一个按钮运行 exe2。 今天我通过远程(终端服务)session 观察客户,exe2 未能运行“找不到文件”错误,但我们检查时 exe1 在同一目录中。 那么我应该使用AppDomain.CurrentDomain.BaseDirectory还是System.Environment.CurrentDirectory ?
谢谢
如果您想在与您的应用程序相同的目录中查找文件, AppDomain.CurrentDomain.BaseDirectory
是正确的选择。
Environment.CurrentDirectory
是一个可以并且将在运行应用程序的过程中发生变化的值。 例如,使用默认参数,WinForms 中的 OpenFileDialog 会将此值更改为从中选择文件的目录。
AppDomain.CurrentDomain.BaseDirectory
返回加载当前应用程序域的目录。
System.Environment.CurrentDirectory
返回当前系统目录。
在您的情况下, AppDomain.CurrentDomain.BaseDirectory
是最好的解决方案。
您应该使用AppDomain.CurrentDomain.BaseDirectory
。
例如,在 windows 服务应用程序中:
System.Environment.CurrentDirectory
将返回C:\Windows\system32
尽管
AppDomain.CurrentDomain.BaseDirectory
将返回 [Application.exe 位置]
另一个需要注意的重要因素是AppDomain.CurrentDomain.BaseDirectory
是一个只读属性,而Environment.CurrentDirectory
可以是其他必要的属性:
// Change the directory to AppDomain.CurrentDomain.BaseDirectory
Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
据我了解,您应该使用BaseDirectory
。 CurrentDirectory
可能会在程序执行过程中发生变化。
在 Visual Studio 2010 测试项目中,如果启用编辑测试设置的部署选项,AppDomain.CurrentDomain.BaseDirectory 指向 TestResults\Out 文件夹(不是 bin\debug)。 虽然,默认设置指向 bin\debug 文件夹。
在这里,我找到了令人信服的答案。
为什么 AppDomain.CurrentDomain.BaseDirectory 在 asp.net 应用程序中不包含“bin”?
我也经历了这几天,因为我正在使用
Environment.CurrentDirectory
因为它在生产服务器上给了我问题,但在我的本地服务器上运行良好,
所以,我尝试了
System.AppDomain.CurrentDomain.BaseDirectory;
它在环境中都对我有用。
所以,正如所有人所说,我们应该始终使用 go
System.AppDomain.CurrentDomain.BaseDirectory;
因为它检查当前域目录的路径。
查看更多信息
我通常使用类似的东西:
string AppPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
AppPath = AppPath.Replace("file:\\", "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.