19

我有一个在主 GUI 应用程序下嵌套两层以上的类库,在该嵌套类库中我希望能够访问主应用程序名称。

在 .Net 3.5 下,您可以调用 Application.ProductName 从 Assembly.cs 文件中检索值,但我无法识别 WPF 中的等价物。如果我使用反射和 GetExecutingAssembly 那么它会返回类库的详细信息吗?

谢谢

4

7 回答 7

33

您可以使用Assembly.GetEntryAssembly()获取 EXE 程序集,然后可以使用反射从中获取 AssemblyProductAttribute。

这假定已在 EXE 程序集上设置了产品名称。WinFormsApplication.ProductName属性实际上是在包含主窗体的程序集中查找的,因此即使 GUI 是在 DLL 中构建的,它也可以工作。要在 WPF 中复制它,您将使用Application.Current.MainWindow.GetType().Assembly(并再次使用反射来获取属性)。

于 2010-02-23T20:04:27.570 回答
7

这是我用来获取产品名称的另一种解决方案

Public Shared Function ProductName() As String
    If Windows.Application.ResourceAssembly Is Nothing Then 
        Return Nothing
    End If

    Return Windows.Application.ResourceAssembly.GetName().Name
End Sub
于 2012-04-26T21:33:11.623 回答
6

在 wpf 中有很多方法可以做到这一点,在这里你可以找到其中的两个。

using System;`
using System.Windows;
String applicationName = String.Empty;

//one way
applicationName = AppDomain.CurrentDomain.FriendlyName.Split('.')[0];

 //other way
applicationName = Application.ResourceAssembly.GetName().Name;
于 2015-10-06T07:25:38.180 回答
4

如果您需要像我一样获取描述性产品名称,那么此解决方案可能很有用:

 // Get the Product Name from the Assembly information
 string productName = String.Empty;
 var list = Application.Current.MainWindow.GetType().Assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), true);
 if (list != null)
 {
   if (list.Length > 0)
   {
     productName = (list[0] as AssemblyProductAttribute).Product;
   }
 }

它返回您在 AssemblyInfo.cs 文件中为“AssemblyProduct”属性设置的任何内容,例如“Widget Engine Professional”之类的内容。

于 2014-08-22T06:28:27.863 回答
3

根据上面的答案,这立即奏效:

var productName = Assembly.GetEntryAssembly()
    .GetCustomAttributes(typeof(AssemblyProductAttribute))
    .OfType<AssemblyProductAttribute>()
    .FirstOrDefault().Product;
于 2016-04-02T14:14:45.850 回答
3

如果您正在寻找装配信息提供的值,例如标题...

在此处输入图像描述

...然后你必须得到这样的自定义属性:

using System.Linq;
using System.Reflection;
using System.Windows;

namespace WpfApp1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Title = (Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute)).SingleOrDefault() as AssemblyTitleAttribute)?.Title;
        }
    }
}

在此处输入图像描述

于 2018-03-07T11:06:54.493 回答
2

您需要的答案是:

Path.GetFileName(Assembly.GetEntryAssembly().GetName().Name)
于 2011-04-09T13:16:32.687 回答