如何通过ASP.NET C#中的代码获取项目名称(程序集?)

时间:2013-11-26 17:07:32

标签: c# reflection .net-assembly assembly-name

我正在尝试通过代码(TestGetAssemblyName)获取项目名称:

enter image description here

我已经尝试了System.Reflection.Assembly.GetExecutingAssembly().GetName().Name但这会返回一些奇怪的混乱字符,看起来是动态生成的。有没有办法让TestGetAssemblyName通过代码返回给我?

2 个答案:

答案 0 :(得分:1)

您在解决方案资源管理器中阅读的内容与已编译的程序集名称或程序集标题完全无关。此外,它不会写在已编译的程序集中的任何位置,因此您无法从代码中访问该名称。

假设MyType是程序集中定义的类型,您可以使用AssemblyTitleAttribute属性(通常在AssemblyInfo.cs中定义)来读取给定标题(与编译的程序集名称或代码名称空间无关):

var assembly = typeof(MyType).Assembly;
var attribute = assembly
    .GetCustomAttributes(typeof(AssemblyTitleAttribute), true)
    .OfType<AssemblyTitleAttribute>()
    .FirstOrDefault();

var title = attribute != null ? attribute.Title : "";

这个(AssemblyTitleAttribute)只是AssemblyInfo.cs中定义的属性之一,选择最符合您要求的属性。

另一方面,您可以使用程序集名称(来自Name的{​​{1}}属性)来获取已编译的程序集名称(同样,这可能与程序集标题和项目标题不同)。

修改
要使它成为单行,你必须把它(当然!)放在代码中的某个地方:

Assembly

用作:

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

答案 1 :(得分:0)

我看到你的项目是一个网站。

问题是网站会为您拥有的每个文件夹生成一个dll。这就是各种App_Web_asdkfjh.dll。

如果您发布网站,VS会将所有这些DLL合并为一个。您可以在部署项目的属性中为此命名,甚至包括项目名称。

如果没有部署项目,您就会看到随机的文件名。