获取WinForms应用程序的正确方法是什么';的名字
本文关键字:是什么 方法 WinForms 应用程序 获取 | 更新日期: 2023-09-27 18:26:36
我可以做这个
return Assembly.GetEntryAssembly().GetName().Name;
或
return Path.GetFileNameWithoutExtension(Application.ExecutablePath);
两者都会给出所需的应用程序名称吗?如果是这样,获取应用程序名称的标准方法是什么?如果这仍然是一个没有胜利的局面,有没有什么方法比另一种更快?或者还有其他正确的方法吗?
查看Application.ProductName和Application.ProductVersion
根据您认为的应用程序名称,甚至还有第三个选项:获取程序集标题或产品名称(这些通常在AssemblyInfo.cs
中声明):
object[] titleAttributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), true);
if (titleAttributes.Length > 0 && titleAttributes[0] is AssemblyTitleAttribute)
{
string assemblyTitle = (titleAttributes[0] as AssemblyTitleAttribute).Title;
MessageBox.Show(assemblyTitle);
}
或:
object[] productAttributes = Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), true);
if (productAttributes.Length > 0 && productAttributes[0] is AssemblyProductAttribute)
{
string productName = (productAttributes[0] as AssemblyProductAttribute).Product;
MessageBox.Show(productName);
}
这取决于如何定义"应用程序名称"。
Application.ExecutablePath
返回启动应用程序的可执行文件的路径,包括可执行文件名,这意味着如果有人重命名该文件,则值会更改。
Assembly.GetEntryAssembly().GetName().Name
返回程序集的简单名称。这通常是但不一定是程序集清单文件的文件名,减去其扩展名
因此,GetName().Name似乎更可靠。
对于更快的,我不知道。我认为ExecutablePath比GetName()更快,因为在GetName(()中需要Reflection,但这应该被衡量。
编辑:
尝试构建此控制台应用程序,运行它,然后尝试使用Windows文件资源管理器重命名可执行文件名,双击重命名的可执行文件直接再次运行
ExecutablePath反映了更改,程序集名称仍然是相同的
using System;
using System.Reflection;
using System.Windows.Forms;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Assembly.GetEntryAssembly().GetName().Name);
Console.WriteLine(Application.ExecutablePath);
Console.ReadLine();
}
}
}