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?
Take a look at Application.ProductName and Application.ProductVersion
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);
}
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With