Search code examples
c#reflection.net-assemblyassembly-name

How to get the project name via code in ASP.NET C# (assembly?)


I'm trying to get the project name via code (TestGetAssemblyName):

enter image description here

I've tried System.Reflection.Assembly.GetExecutingAssembly().GetName().Name but this returns some weird jumble of characters, looks dynamically generated. Is there a way to get TestGetAssemblyName returned to me via code?


Solution

  • What you read in Solution Explorer is completely unrelated to compiled assembly name or assembly title. Moreover it won't be written anywhere in your compiled assembly so you can't access that name from code.

    Assuming MyType is a type defined in your assembly you can use AssemblyTitleAttribute attribute (usually defined in AssemblyInfo.cs) to read given title (unrelated to compiled assembly name or code namespace):

    var assembly = typeof(MyType).Assembly;
    var attribute = assembly
        .GetCustomAttributes(typeof(AssemblyTitleAttribute), true)
        .OfType<AssemblyTitleAttribute>()
        .FirstOrDefault();
    
    var title = attribute != null ? attribute.Title : "";
    

    This (AssemblyTitleAttribute) is just one of the attributes defined in AssemblyInfo.cs, pick the one that best fit your requirement.

    On the other way you may use assembly name (Name property from Assembly) to get compiled assembly name (again this may be different from assembly title and from project title too).

    EDIT
    To make it single line you have to put it (of course!) somewhere in your code:

    public static class App
    {
        public static string Name
        {
             get
             {
                 if (_name == null)
                 {
                     var assembly = typeof(App).Assembly;
                     var attribute = assembly
                         .GetCustomAttributes(typeof(AssemblyTitleAttribute), true)
                         .OfType<AssemblyTitleAttribute>()
                         .FirstOrDefault();
    
                    _name = attribute != null ? attribute.Title : "";
                 }
    
                 return _name;
             }
        }
    
        private string _name;
    }
    

    To be used as:

    <a href="server/App?appName=<% App.Name %> />