Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 435
VansFannel Avatar asked Oct 21 '25 11:10

VansFannel


2 Answers

Yeah, you have to take into account @Hagai Shahar answer, the way to go would be using AppDomain.CurrentDomain.BaseDirectory

like image 65
David Noreña Avatar answered Oct 22 '25 23:10

David Noreña


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);
like image 29
Zohaib Aslam Avatar answered Oct 22 '25 23:10

Zohaib Aslam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!