How to get exe application name and version in C# Compact Framework

cja picture cja · Feb 12, 2013 · Viewed 90.4k times · Source

My application has an exe and uses some DLLs. I am writing all in C#.

In one DLL I want to write a method to get the application name and version from the version information in the exe.

I understand that in full .NET I could use GetEntryAssembly, but that that is unavailable in CF.

Answer

ctacke picture ctacke · Feb 13, 2013

Getting the app name:

System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;

Getting the version:

System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

You might want to use GetCallingAssembly() or getting the assembly by type (e.g. typeof(Program).Assembly) if your DLL is trying to get the EXE version and you don't have immediate access to it.

EDIT

If you have a DLL and you need the name of the executable you have a few options, depending on the use case. You can get the Assembly from a type contained in the EXE assembly, but since it would be rare for the DLL to reference the EXE, it requires the EXE pass in an object of that type.

Version GetAssemblyVersionFromObjectType(object o)
{
    o.GetType().Assembly.GetName().Version;
}

You could also do a little bit of an end-run like this:

[DllImport("coredll.dll", SetLastError = true)]
private static extern int GetModuleFileName(IntPtr hModule, StringBuilder lpFilename, int nSize);

...

var name = new StringBuilder(1024);
GetModuleFileName(IntPtr.Zero, name, 1024);
var version = Assembly.LoadFrom(name.ToString()).GetName().Version;