C# 获取类库中的当前目录

C# 获取类库中的当前目录,c#,json,wpf,windows-8,windows-8.1,C#,Json,Wpf,Windows 8,Windows 8.1,我正在用.NETFramework4.5.1开发一个C#库,以便在Windows8.1桌面应用程序中使用它 在这个库项目中,我有一个JSON文件,我想加载它。首先,我尝试使用以下内容获取当前目录: string currentDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); 但是,我已经对它进行了测试,并且Assembly.GetEntryAssembly()为空 也许,我可以使用资源文件而不是JSON文件 方

我正在用.NETFramework4.5.1开发一个C#库,以便在Windows8.1桌面应用程序中使用它

在这个库项目中,我有一个
JSON
文件,我想加载它。首先,我尝试使用以下内容获取当前目录:

string currentDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
但是,我已经对它进行了测试,并且
Assembly.GetEntryAssembly()
为空

也许,我可以使用资源文件而不是JSON文件

方法如下:

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);
}
private void LoadData()
{
字符串currentDir=
GetDirectoryName(Assembly.GetEntryAssembly().Location);
字符串文件=
路径组合(currentDir、cardsDir、cardsFile);
字符串json=
ReadAllText(文件);
Deck=JsonConvert.DeserializeObject(json);
}
有什么想法吗?有更好的方法吗?如何获取当前目录?

试试这个

Environment.CurrentDirectory
这将返回应用程序的当前工作目录。现在,您可以访问与应用程序相关的任何文件

string currentDir = Path.GetDirectoryName(Environment.CurrentDirectory);

请注意,
Environment.CurrentDirectory
不一定返回包含应用程序文件的目录。这取决于您从何处启动应用程序

例如,如果exe文件位于
C:\User\ProgramName\prog.exe
,但您从
cmd
启动应用程序,如下所示:

C:\> C:\User\ProgramName\prog.exe
…环境.CurrentDirectory的结果将是
C:\
,而不是
C:\User\programmName

此外,它也发生在快捷方式中:

请参阅“开始于”属性?如果设置此选项,它将成为Environment.CurrentDirectory的结果,因为应用程序将从那里启动

另一种解决方案是获取运行应用程序的程序集的位置,如下所示:


typeof(Program).Assembly.Location

是的,你必须考虑@Hagai Shahar的答案,方法是使用AppDomain.CurrentDomain.BaseDirectory

我认为这将产生与他在
字符串currentDir
中的第一行相同的结果,谢谢,
Environment.CurrentDirectory
返回当前目录。