Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way of getting my WinForms application's name?

I could do this

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

or

return Path.GetFileNameWithoutExtension(Application.ExecutablePath);

Would both give the desired application name always? If so which is a more standard way of getting application name? If its still a no-win situation is there anything like one method is faster than the other? Or else is there any other right approach?

like image 924
nawfal Avatar asked Mar 03 '12 10:03

nawfal


3 Answers

Take a look at Application.ProductName and Application.ProductVersion

like image 126
Nikola Markovinović Avatar answered Sep 28 '22 04:09

Nikola Markovinović


Depending on what you're considering to be the application name, there's even a third option: get the assembly title or product name (those are usually declared in 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);
}

or:

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);
}
like image 36
Yuriy Guts Avatar answered Sep 28 '22 02:09

Yuriy Guts


It depends how you define 'application name'.

Application.ExecutablePath returns the path for the executable file that started the application, including the executable name, this means that if someone rename the file the value changes.

Assembly.GetEntryAssembly().GetName().Name returns the simple name of the assembly. This is usually, but not necessarily, the file name of the manifest file of the assembly, minus its extension

So, the GetName().Name seem more affidable.

For the faster one, I don't know. I presume that ExecutablePath is faster than GetName() because in the GetName() requires Reflection, but this should be measured.

EDIT:

Try to build this console app, run it and then try to rename the executable file name using the Windows File Explorer, run again directly with the double click on the renamed executable.
The ExecutablePath reflects the change, the Assembly name is still the same

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();
        }
    }
}
like image 32
Steve Avatar answered Sep 28 '22 04:09

Steve