tags:

views:

3572

answers:

4

What is the best way to get the application name (i.e MyApplication.exe) of the executing assembly from a referenced class library in C#?

I need to open the application's app.config to retrieve some appSettings variables for the referenced DLL.

+7  A: 
string exeAssembly = Assembly.GetEntryAssembly().FullName;
Ray Hayes
That requires using System.Reflection?
Michael Kniskern
Yes, that's in the System.Reflection namespace.
Judah Himango
This was returned from that call: MyApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
Michael Kniskern
To find out which is the required namespace just select in the above code the Assembly and Ctrl + Shift + F10 ...
YordanGeorgiev
+5  A: 

If you want to get the current appdomain's config file, then all you need to do is:

ConfigurationManager.AppSettings....

(this requires a reference to System.Configuration of course).

To answer your question, you can do it as Ray said (or use Assembly.GetExecutingAssembly().FullName) but I think the problem is easier solved using ConfigurationManager.

Ben Scheirman
Will this solution work with asp.net application? The referenced class library can be used by WinForms and ASP.NET apps
Michael Kniskern
yep, that's the beauty of ConfigurationManager. It selects whichever app.config/web.config is appropriate for the app domain.This was introduced in .NET 2.0.
Ben Scheirman
I just ran a test with an asp.net application and a WinFomrs application and it worked for both environments. I am currently running a test with a WCF service. This is web I was running into issues.
Michael Kniskern
Is the dll you're talking about in a separate app domain?
Ben Scheirman
This worked for ASP.NET and WinForms application, but it does not work for a WCF service.
Michael Kniskern
@Ben - How would I figure that out?
Michael Kniskern
@Ben - Your solution also worked with a WCF Service.
Michael Kniskern
A: 

You should never couple your libraries to a consumer (in this case Web, WinForm or WCF app). If your library needs configuration settings, then GIVE it to the library. Don't code the library to pull that data from a consumer's config file. Provide overloaded constructors for this (that's what they are for). If you've ever looked at the ConfigurationManager.AppSettings object, it is simply a NameValueCollection. So create a constructor in your library to accept a NameValueCollection and have your consumer GIVE that data to the library.

//Library public class MyComponent { //Constructor public MyComponent(NameValueCollection settings) { //do something with your settings now, like assign to a local collection } }

//Consumer class Program { static void Main(string[] args) { MyComponent component = new MyComponent(ConfigurationManager.AppSettings); } }

+1  A: 

To get the exact name without versions, etc. use:

string appName = Assembly.GetEntryAssembly().GetName().Name;

Works with .NET v1.1 and later.

AOI Karasu