wpf 获取类库中的当前目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27233853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get current dir in a class library
提问by VansFannel
I'm developing a C# library with .Net Framework 4.5.1 to use it in a Windows 8.1 desktop application.
我正在使用 .Net Framework 4.5.1 开发 C# 库,以便在 Windows 8.1 桌面应用程序中使用它。
Inside this library project I have a JSONfile, and I want to load it. First, I have tried to get current directory with this:
在这个库项目中,我有一个JSON文件,我想加载它。首先,我试图用这个获取当前目录:
string currentDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
But, I have test it and Assembly.GetEntryAssembly()is null.
但是,我已经测试过它并且Assembly.GetEntryAssembly()是空的。
Maybe, I can use a resource file instead of a JSON file.
也许,我可以使用资源文件而不是 JSON 文件。
This is the method:
这是方法:
private void LoadData()
{
string currentDir =
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string file =
Path.Combine(currentDir, cardsDir, cardsFile);
string json =
File.ReadAllText(file);
Deck = JsonConvert.DeserializeObject<Card[]>(json);
}
Any idea? Is there a better approach? How can I get current dir?
任何的想法?有没有更好的方法?我怎样才能得到当前的目录?
回答by Zohaib Aslam
try this
尝试这个
Environment.CurrentDirectory
this will return the current working directory of your application. now you can access any file relative to your application
这将返回应用程序的当前工作目录。现在您可以访问与您的应用程序相关的任何文件
string currentDir = Path.GetDirectoryName(Environment.CurrentDirectory);
回答by Hagai Shahar
Pay attention that Environment.CurrentDirectorydoes not necessarilyreturn the directory that contains the application files. It depends on where you started the application from.
注意Environment.CurrentDirectory不一定返回包含应用程序文件的目录。这取决于您从何处启动应用程序。
For example, if the exe file is located at C:\User\ProgramName\prog.exebut you start the application from cmdlike this:
例如,如果 exe 文件位于C:\User\ProgramName\prog.exe但您从以下位置启动应用程序cmd:
C:\> C:\User\ProgramName\prog.exe
...the result of Environment.CurrentDirectorywill be C:\and not C:\User\ProgramName.
... Environment.CurrentDirectorywillC:\和 not的结果C:\User\ProgramName。
Furthermore, it happens also in shortcuts:
此外,它也发生在快捷方式中:
See the "Start In" property? If this is set it will become the result of Environment.CurrentDirectorybecause the application will be started from there.
看到“开始于”属性了吗?如果设置了它,它将成为结果,Environment.CurrentDirectory因为应用程序将从那里启动。
Another solution is to get the location of the assembly which runs the application, something like this:
另一种解决方案是获取运行应用程序的程序集的位置,如下所示:
typeof(Program).Assembly.Location
typeof(Program).Assembly.Location
回答by David Nore?a
Yeah, you have to take into account @Hagai Shahar answer, the way to go would be using AppDomain.CurrentDomain.BaseDirectory
是的,你必须考虑@Hagai Shahar 的回答,要走的路是使用AppDomain.CurrentDomain.BaseDirectory


