获取winforms应用程序名称的正确方法是什么?

时间:2012-03-03 10:54:07

标签: c# winforms .net-assembly application-name executable-path

我可以这样做:

return Assembly.GetEntryAssembly().GetName().Name;

return Path.GetFileNameWithoutExtension(Application.ExecutablePath);

两者都会提供所需的应用程序名称始终 ??如果是这样,这是获取应用程序名称的更标准方法?如果它仍然是一个不赢的局面,有什么比一种方法更快的速度吗?或者还有其他正确的方法吗?

感谢。

3 个答案:

答案 0 :(得分:11)

答案 1 :(得分:4)

根据您正在考虑的应用程序名称,甚至还有第三种选择:获取程序集标题或产品名称(通常在AssemblyInfo.cs中声明):< / p>

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

答案 2 :(得分:1)

这取决于您如何定义应用程序名称&#39;。

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