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

后端 未结 12 983
我寻月下人不归
我寻月下人不归 2020-12-07 18:39

How do I obtain the version number of the calling web application in a referenced assembly?

I\'ve tried using System.Reflection.Assembly.GetCallingAssembly().GetName

12条回答
  •  一生所求
    2020-12-07 19:08

    I encountered a similar problem, and thought you might find the solution useful.

    I needed to report the current application version (of a web application project) from a custom server control, where the server control was contained in a different library. The problem was that the "easiest" assembly getters did not provide the right assembly.

    • Assembly.GetExecutingAssembly() returned the assembly containing the control; not the application assembly.
    • Assembly.GetCallingAssembly() returned different assemblies depending on where I was at in the call tree; usually System.Web, and sometimes the assembly containing the control.
    • Assembly.GetEntryAssembly() returned null.
    • new StackTrace().GetFrames()[idx].GetMethod().DeclaringType.Assembly retrieves the assembly of a frame in the stack trace at index idx; however, besides being inelegant, expensive, and prone to miscalculation on the frame index, it is possible for the stack trace to not contain any calls to the application assembly.
    • Assembly.GetAssembly(Page.GetType()) scored me the App_Web_@#$@#$%@ assembly containing the dynamically generated page. Of course, the dynamic page inherits a class from my application assembly, so that led to the final solution:

    Assembly.GetAssembly(Page.GetType().BaseType)
    

    With the assembly reference in hand, you can drill to the version through its name:

    var version = Assembly.GetAssembly(Page.GetType().BaseType)
                          .GetName()
                          .Version;
    

    Now, this solution works because I had a reference to a type from the application assembly. We don't use any pages that do not inherit from a code behind, so it happens to be effective for us, but your mileage may vary if your organization's coding practices are different.

    Happy coding!

提交回复
热议问题