开发者

Read AssemblyTitle attribute in ASP.NET

开发者 https://www.devze.com 2023-04-03 03:20 出处:网络
I use code below to read AssemblyTitle attribute of .NET apps, unfortunately Assembly.GetEntryAssembly() always 开发者_开发知识库return Null in ASP.NET app. How to read AssemblyTitle in ASP.NET app?

I use code below to read AssemblyTitle attribute of .NET apps, unfortunately Assembly.GetEntryAssembly() always 开发者_开发知识库return Null in ASP.NET app. How to read AssemblyTitle in ASP.NET app?

  public static string Title
  {
      get
      {
          var attributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
          if (attributes.Length > 0)
          {
              var titleAttribute = (AssemblyTitleAttribute)attributes[0];
              if (titleAttribute.Title.Length > 0)
                  return titleAttribute.Title;
          }
          return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().CodeBase);
      }
  }


You must have a type that you know is defined in the same assembly that contains the AssemblyTitle. Then you can do:

typeof(MyType).Assembly.GetCustomAttributes

Note that (for what I know) there isn't any other bulletproof method.

For example using HttpContext.Current doesn't work if you want to do it not during a web request (so you can do it on response of a user action, but not from a separate thread, or from a static initializer, or from global.asax)

Some similar readings (full of half successes):

GetEntryAssembly for web applications

Using the Web Application version number from an assembly (ASP.NET/C#)


I use the following in asp.net web app:

if (ApplicationDeployment.IsNetworkDeployed)
    return ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

Edit: Sorry, thats just the version, not the title! I combined your version and mine:

System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); 

That gets the assembly title attribute just fine. The difference is in GetExecutingAssembly() versus your GetEntryAssembly().

0

精彩评论

暂无评论...
验证码 换一张
取 消