Search code examples
c#jsonwpfwindows-8windows-8.1

Get current dir in a class library


I'm developing a C# library with .Net Framework 4.5.1 to use it in a Windows 8.1 desktop application.

Inside this library project I have a JSON file, and I want to load it. First, I have tried to get current directory with this:

string currentDir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

But, I have test it and Assembly.GetEntryAssembly() is null.

Maybe, I can use a resource file instead of a JSON file.

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?


Solution

  • 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);