4

I need to obtain the version of my Windows service programmatically and store it in a string. Then, I'll append the version to my display name and service name in the ProjectInstaller class. Right now I'm getting an empty string and I'm having trouble debugging my setup project. Here's my current code:

        string version = null;
        try
        {
            Assembly exeAssembly = Assembly.GetEntryAssembly();
            Type attrType = typeof(AssemblyFileVersionAttribute);
            object[] attributes = exeAssembly.GetCustomAttributes(attrType, false);
            if (attributes.Length > 0)
            {
                AssemblyFileVersionAttribute verAttr = (AssemblyFileVersionAttribute)attributes[0];
                if (verAttr != null)
                {
                    version = verAttr.Version;
                }
            }
        }
        catch
        {
        }
        if (version == null)
        {
            version = string.empty;
        }
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
jmac
  • 245
  • 5
  • 21

1 Answers1

10
var version = Assembly.GetExecutingAssembly().GetName().Version;
return version.ToString();

Will return it in 1.0.0.0 form.

Or, you can use the version.Major + "." + version.Minor to get just the first two numbers.

Alternatively, if you want the file version...

var fvi = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);
return fvi.FileVersion;
John Gietzen
  • 48,783
  • 32
  • 145
  • 190
  • This worked! How do I preserve the leading zeros (i.e., 050000.01.01.00 is showing up as 50000.1.1.0)? – jmac Jun 11 '10 at 13:24
  • If you know how many leading zeroes are needed you can use something like `version.Major.ToString().PadLeft(10, '0') + "." + version.Minor`, etc. – John Gietzen Jun 11 '10 at 14:02
  • Also, if this answer was helpful to you, would you mind clicking the "Up-arrow" to vote for it? Thanks. – John Gietzen Jun 11 '10 at 14:03
  • I did click the check mark. When I tried to click the "Up-arrow", it stated that "Vote Up requires 15 reputation". – jmac Jun 11 '10 at 14:37