WPF中的Application.ProductName等价物?

时间:2010-02-23 19:44:27

标签: c# wpf

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

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

由于

7 个答案:

答案 0 :(得分:31)

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

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

答案 1 :(得分: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

答案 2 :(得分:5)

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

答案 3 :(得分: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”这样的东西。

答案 4 :(得分:3)

根据上面的答案,这很有效:

var productName = Assembly.GetEntryAssembly()
    .GetCustomAttributes(typeof(AssemblyProductAttribute))
    .OfType<AssemblyProductAttribute>()
    .FirstOrDefault().Product;

答案 5 :(得分:2)

您需要的答案是:

Path.GetFileName(Assembly.GetEntryAssembly().GetName().Name)

答案 6 :(得分:1)

如果您要查找装配信息提供的值,例如标题......

enter image description here

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

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

enter image description here