How to get the current directory on a class library?
Asked Answered
M

2

29

I've been looking around but I have not found a solution for this problem: I want to create a class library that has a configuration file under a sub-directory called Configuration. I want that class library to be deployed anywhere and I want it to find its configuration files by knowing its own location.

Previous attempts with Assembly.GetExecutingAssembly().Location did not work.
It would return temp locations such as

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\7c00e0a3\38789d63\assembly\dl3\9c0a23ff\18fb5feb_6ac3c901

instead of the desired

bin/Configuration path.

So:

  1. Can a class library be aware of its own location on disk?
  2. How would I go about witting test scripts for this functionality since it seems that directories change based on how you run the app (debugging inside VS, deploying on IIS, etc)
Mors answered 22/4, 2009 at 17:3 Comment(3)
Why not include the configuration in the application's app.config file and use ConfigurationManager in your class libraries?Amphiarthrosis
You might want to clarify your question (for better searchability later) that this is ASP.NET. For desktop applications, GetExecutingAssembly() works just fine.Distributary
@Justin: I want the Class Library to be independent of the caller application. @Stu: Both. I want to create a class library that could be used for both Console Apps and Web Apps. The class library should not care about who's calling it.Mors
P
46

This should work -

string assemblyFile = (
    new System.Uri(Assembly.GetExecutingAssembly().CodeBase)
).AbsolutePath;
Petrochemical answered 22/4, 2009 at 17:10 Comment(2)
would: System.Reflection.Assembly.GetExecutingAssembly ().Location not give the same info...?Tonguing
@Tonguing not when there's shadow copying. try it in unit test, for example, and it'll be wrongPetrochemical
T
3

The below code worked for me to get the physical path of the Images folder in-class library file.

string fullFilePath = Path.Combine((new System.Uri(Assembly.GetExecutingAssembly().CodeBase)).AbsolutePath.Split(new string[] { "/bin" }, StringSplitOptions.None)[0]
                          , "@/Images/test.png");

I hope, it will help someone.

Toothy answered 19/3, 2020 at 14:5 Comment(1)
I think this one is working for me, so thanks, @RajeevKumarCelle

© 2022 - 2024 — McMap. All rights reserved.