views:

45

answers:

1

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;
        }
A: 
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
This worked! How do I preserve the leading zeros (i.e., 050000.01.01.00 is showing up as 50000.1.1.0)?
jmac
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
Also, if this answer was helpful to you, would you mind clicking the "Up-arrow" to vote for it? Thanks.
John Gietzen
I did click the check mark. When I tried to click the "Up-arrow", it stated that "Vote Up requires 15 reputation".
jmac
Ah, awesome, sorry.
John Gietzen