Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# How to get the version of This current executable .exe

Tags:

c#

version

I have been using this code to obtain my programs version:

public string progVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

However, it doesn't always seem to grab the version I'm expecting. I don't really understand how this works entirely or what it's doing.

I think it is impart because I'm launching my program from another program then it appears to grab the version of the program that launched it instead, or the 'GetExecutingAssembly()' I'm assuming references the program that executed my program, like so:

System.Diagnostics.Process.Start(my_programs_path);

Is there a more reliable way to get the program version of the actual program at the time I ask for it?

Perhaps even launch my program without leaving some kind of trail, as if the user themselves just launched it.

Thanks for any help!

like image 904
Eric Avatar asked Aug 27 '16 18:08

Eric


2 Answers

GetExecutingAssembly() returns the assembly that contains the method thaτ calls it. If you call it from a library you will always get the version of the library not the application executable.

To get the application's executable use GetEntryAssembly()

Consider the following example:

In AssemblyA:

class VersionTest
{
  void Test()
  {
    Console.Write("Executing assembly: {0}\n", Assembly.GetExecutingAssembly().GetName().ToString()); // returns AssemblyA
    Console.Write("Entry assembly: {0}\n", Assembly.GetEntryAssembly().GetName().ToString());         // returns AssemblyB
  }
}

In AssemblyB:

class Program
{
   void Main()
   {
      var ver = new VersionTest();
      ver.Test();
   }
}
like image 176
P. Kouvarakis Avatar answered Sep 25 '22 00:09

P. Kouvarakis


You could use the Assembly property of a known type via typeof which is defined in your application to ensure you got the 'correct' assembly and then retrieve the version of that, e.g.

typeof(YourKnownType).Assembly.GetName().Version.ToString();
like image 37
tengobash Avatar answered Sep 25 '22 00:09

tengobash