Get executing assembly name from referenced DLL in C#

前端 未结 8 850
野性不改
野性不改 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:28

    You can get the assembly through the class type...

    typeof(MyClass).Assembly
    
    0 讨论(0)
  • 2020-12-08 19:28

    For the short name of an assembly from a class instance:

    Me.GetType ().Assembly.GetName().Name
    
    0 讨论(0)
  • 2020-12-08 19:38

    To get the answer to the question title:

    // Full-name, e.g. MyApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
    string exeAssembly = Assembly.GetEntryAssembly().FullName;
    
    // or just the "assembly name" part (e.g. "MyApplication")
    string exeAssemblyName = Assembly.GetEntryAssembly().GetName().Name;
    

    As mentioned by @Ben, since you mention wanting to get the configuration information, use the ConfigurationManager class.

    0 讨论(0)
  • 2020-12-08 19:40

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

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

    Works with .NET v1.1 and later.

    0 讨论(0)
  • 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);
      }
    }
    
    0 讨论(0)
  • 2020-12-08 19:45

    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.

    0 讨论(0)
提交回复
热议问题