Get executing assembly name from referenced DLL in C#

前端 未结 8 849
野性不改
野性不改 2020-12-08 19:20

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 applicat

8条回答
  •  醉梦人生
    2020-12-08 19:41

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

提交回复
热议问题