Environment.CurrentDirectory 与 System.Reflection
在以下获取正在执行的程序集的工作目录的方法中,是否有建议将哪一种视为最佳实践?我从开发人员那里得知,方法 1 在 Windows 7 SP1 64 位上有时会失败,除非以提升的权限运行(以管理员身份运行)。但方法2始终有效。前者有时会失败是否有原因?
方法 1:
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location())
方法 2:
Environment.CurrentDirectory
Out of the following methods to get the working directory of an executing assembly, is there a recommendation on which one is considered Best Practice? I hear from my developers that Method 1 fails on Windows 7 SP1 64-bit sometimes, unless run with elevated permissions (Run as Administrator). But Method 2 works all the time. Is there a reason that the former would fail sometimes?
Method 1:
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location())
Method 2:
Environment.CurrentDirectory
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Environment.CurrentDirectory
是获取工作目录的方法。使用反射也可能会更慢。但要小心:这两种方法并不相同:方法 A 始终返回存储程序集的目录,其中
Environment.CurrentDirectory
为您提供当前工作目录,该目录可以在应用程序生命周期内更改,因为Environment.CurrentDirectory
也可用于设置工作目录,并且其他方法也可以更改它(例如文件打开/保存对话框)。Environment.CurrentDirectory
is the way to go as it is there for getting the working directory. Using reflection is also possibly slower.BUT be careful: the two methods are NOT the same: Method A returns allways the directory where the assembly is stored in, where as
Environment.CurrentDirectory
gives you the current working directory which can change during the application lifetime, asEnvironment.CurrentDirectory
can also be used to set the working directory and other method could also change it (e.g. file open/save dialogs).