Solved

vertion of C#.net program

Posted on 2010-08-28
2
278 Views
Last Modified: 2013-12-17
System.enviroment. version
will this help me find version .net a c#.net program  is?
I have a program that I have on a vista machine and realized - i need to run compatible with XP to run correctly.
I cannot see code- because a programmer just gave me program to see if that is what I am trying to do.

what I want to know - ( i have visual studio 2008)  when I open program in there- is there  a way to see what version programmer created it in?
I don't understand System.eviroment.version- where I would input that?
thank you
0
Comment
Question by:davetough
2 Comments
 
LVL 10

Accepted Solution

by:
Marcjev earned 250 total points
ID: 33549212
Below some code which does it all.

To determine the version of a .net exe in C#, you have to load it. This only succeeds for .net programs and not for 'old' code. LoadVersion first tries the .NET way, and if this not succeeds, does win32 calls so it even works for old code.  See my code below.

(The is also some code, to get a build version given a com guid (like CheckMinVersionGuid) but ignore that in your case...) LoadVersion is the thing you probably need.
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Win32;

namespace VersionCheck
{
    //{518B8648-7878-46a6-80B8-C63917D1C889}
    [ProgId("MVESqlNative"), ClassInterface(ClassInterfaceType.AutoDual), Guid("518B8648-7878-46a6-80B8-C63917D1C889")]
    public class MVEVersionChecker
    {

        int nMajor, nMinor, nBuild, nRevision, nMinorRev, nMajorRev;
        //string Name;
        [DllImport("version.dll")]
        private static extern bool GetFileVersionInfo(string sFileName,
             int handle, int size, byte[] infoBuffer);
        [DllImport("version.dll")]
        private static extern int GetFileVersionInfoSize(string sFileName,
             out int handle);
        // The third parameter - "out string pValue" - is automatically 
        // marshaled from ANSI to Unicode: 
        [DllImport("version.dll")]
        unsafe private static extern bool VerQueryValue(byte[] pBlock,
             string pSubBlock, out string pValue, out uint len);
        // This VerQueryValue overload is marked with 'unsafe' because 
        // it uses a short*: 
        [DllImport("version.dll")]
        unsafe private static extern bool VerQueryValue(byte[] pBlock,
             string pSubBlock, out short* pValue, out uint len); 
        public int MajorRev
        {
            get { return nMajorRev; }
            set { nMajorRev = value; }
        }
        public int MinorRev
        {
            get { return nMinorRev; }
            set { nMinorRev = value; }
        }
        public int Revision
        {
            get { return nRevision; }
            set { nRevision = value; }
        }
        public int Build
        {
            get { return nBuild; }
            set { nBuild = value; }
        }
        public int Minor
        {
            get { return nMinor; }
            set { nMinor = value; }
        }
        public int Major
        {
            get { return nMajor; }
            set { nMajor = value; }
        }
        public string LoadVersion(string sPathToFile)
        {
            bool bRetry = false;
            sPathToFile = ExpandEnvironmentVariables(sPathToFile);
            if (!System.IO.File.Exists(sPathToFile))
            {
                return ("0.0.0.0");
            }
            Assembly myAssembly;
            myAssembly = null;

            try
            {
                myAssembly = Assembly.LoadFrom(sPathToFile);
            }
            catch (Exception)
            {
                bRetry = true;
            }
            if ((bRetry == false) && (myAssembly != null))
            {
                string Name = myAssembly.GetName().Name;
                Version vs = myAssembly.GetName().Version;
                nMajor = vs.Major;
                nMajorRev = vs.MajorRevision;
                nMinor = vs.Minor;
                nMinorRev = vs.MinorRevision;
                nBuild = vs.Build;
                nRevision = vs.Revision;
                return (vs.ToString());
            }
            else
            {
                string vs;
                vs = string.Empty;
                try
                {
                    vs = LoadVersionEx(sPathToFile);
                }
                catch (Exception )
                {
                    nMajor = 0;
                    nMinor = 0;
                    nBuild = 0;
                    nRevision = 0;
                    nMajorRev = 0;
                    nMinorRev = 0;
                }
                vs = string.Format("{0}.{1}.{2}.{3}", nMajor, nMinor, nBuild, nRevision);
                return (vs);
            }
        }
        /// <summary>
        /// Retrieve version number, not depending on being a .net dll or exe. 
        /// </summary>
        /// <param name="path">Full path name of exe/dll</param>
        /// <returns>Versionnumber as a string. Fills properties major,minor,build,revision</returns>
        unsafe string GetFileVersionInternal(string path)
        {
            string name = null; 
            int handle = 0; 
            int size = GetFileVersionInfoSize(path, out handle); 
            if (size != 0) 
            { 
                byte[] buffer = new byte[size]; 

                if (GetFileVersionInfo(path, handle, size, buffer)) 
                { 
                    uint len = 0; 
                    short* subBlock = null; 
                    //IntPtr subBlock = IntPtr.Zero;
                    /*
                    if (VerQueryValue(buffer, @"\VarFileInfo\Translation", out subBlock, out len) && len > 2) 
                    {
                        string spv = @"\StringFileInfo\" + subBlock[0].ToString("X4") + subBlock[1].ToString("X4") + @"\FileVersion"; 
                        byte* pVersion = null; 
                        string versionInfo; 
                        if (VerQueryValue(buffer, spv, out versionInfo, out len)) 
                        { 
                            name = versionInfo; 
                        } 
                    }
                    */

                    if (VerQueryValue(buffer, @"\", out subBlock, out len) && len > 2)
                    {
                        UInt32 msb = (UInt32)System.Runtime.InteropServices.Marshal.ReadInt32((IntPtr)subBlock, 8); // Read the dwFileVersionMS field
                        UInt32 lsb = (UInt32)System.Runtime.InteropServices.Marshal.ReadInt32((IntPtr)subBlock, 12); // Read the dwFileVersionLS field

                        nMajor = (int)(msb & 0xFFFF0000) >> 16; // Extract the top 16bits from dwFileVersionMS
                        nMinor = (int)(msb & 0x0000FFFF); // Extract the low 16bits from dwFileVersionMS
                        nBuild = (int)(lsb & 0xFFFF0000) >> 16; // Extract the top 16bits from dwFileVersionLS
                        nRevision = (int)(lsb & 0x0000FFFF); // Extract the low 16bits from dwFileVersionLS
                        name = string.Format("{0}.{1}.{2}.{3}", nMajor, nMinor, nBuild, nRevision);
                    }

                } 
            }
            /*
            if (name == null) 
            { 
                name = Path.GetFileNameWithoutExtension(path); 
            } 
            */
            return name; 
        }
        public string LoadVersionEx(string path)
        {
            return (GetFileVersionInternal(path));
        }       
        /// <summary>
        /// Check version of an executable or dll.
        /// </summary>
        /// <param name="sPath">Full path to exe or dll</param>
        /// <param name="major">Major version</param>
        /// <param name="minor">Minor version</param>
        /// <param name="build">Build version</param>
        /// <param name="rev">Revision version</param>
        /// <returns>True if exe/dll has minimal the requested version</returns>
        public bool CheckMinVersion(string sPath, int major, int minor, int build, int rev)
        {
            LoadVersion(sPath);
            if (major > nMajor)
            {
                return(false);
            } 
            else
            { 
                if (major < nMajor)
                {
                    return true;
                }
                else
                { //major equal
                    if (minor > nMinor)
                    {
                        return (false);
                    }
                    else
                    {
                        if (minor < nMinor)
                        {
                            return (true);
                        }
                        else
                        { // major and minor equal)
                            if (build > nBuild)
                            {
                                return (false);
                            }
                            else
                            {
                                if (build < nBuild)
                                {
                                    return (true);
                                }
                                else
                                {
                                    if (rev <= nRevision)
                                    {
                                        return (true);
                                    }
                                    else
                                    {
                                        return (false);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public string GetAppPath(string sName)
        {
            RegistryKey theKey;
            string sPath;
            try
            {
                theKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths", false);
            }
            catch (Exception)
            {
                return (string.Empty);
            }
            RegistryKey app;
            try
            {
                app = theKey.OpenSubKey(sName);
            }
            catch (Exception)
            {
                theKey.Close();
                return string.Empty;
            }
            if (app == null)
            {
                return string.Empty;
            }


            if (app.GetValue("") != null)
            {
                sPath = app.GetValue("").ToString();
                app.Close();
                theKey.Close();
                return (sPath);
            }
            app.Close();
            theKey.Close();
            return (string.Empty);
        }
        /// <summary>
        /// Check the minimal version given an apppath name
        /// </summary>
        /// <param name="sExe">Name of the exe</param>
        /// <param name="major">Major version</param>
        /// <param name="minor">Minor version</param>
        /// <param name="build">Build version</param>
        /// <param name="rev">Revision version</param>
        /// <returns>True</returns>
        public bool CheckMinVersionAppPath(string sExe, int major, int minor, int build, int rev)
        {
            string spath;
            spath = GetAppPath(sExe);
            if (spath != string.Empty)
            {
                return (CheckMinVersion(spath,major,minor,build,rev));
            }
            return (false);
        }
        /// <summary>
        /// Get Dll or pathname of the codeunit, given a com guid.
        /// </summary>
        /// <param name="sGuid">Com Guid</param>
        /// <returns>Path to the code.</returns>
        public string GetGuidPath(string sGuid)
        {
            RegistryKey theKey;
            RegistryKey inProc = null;
            string sPath;
            bool bRetry = false;
            theKey = Registry.ClassesRoot.OpenSubKey("CLSID", false);
            RegistryKey theGuid;
            try
            {
                theGuid = theKey.OpenSubKey(sGuid);
            }
            catch (Exception)
            {
                theKey.Close();
                return string.Empty;
            }
            if (theGuid == null)
            {
                theKey.Close();
                return string.Empty;
            }
            try
            {
                inProc = theGuid.OpenSubKey("InProcServer32");
            }
            catch (Exception)
            {
                //do nothing
                bRetry = true;
            }
            if (bRetry)
            {
                try
                {
                    inProc = theGuid.OpenSubKey("LocalServer32");
                }
                catch (Exception)
                {
                    theKey.Close();
                    theGuid.Close();
                    return string.Empty;
                }
            }
            try
            {
                sPath = inProc.GetValue("").ToString();
            }
            catch (Exception)
            {
                inProc.Close();
                theGuid.Close();
                theKey.Close();
                return string.Empty;
            }
            if (sPath == "mscoree.dll")
            {
                //special case of C# based com dll. Search further
                string sCodeBase = inProc.GetValue("CodeBase").ToString();
                Uri theUri = new Uri(sCodeBase);
                sPath = theUri.AbsolutePath;
            }
            inProc.Close();
            theGuid.Close();
            theKey.Close();
            return sPath;
        }
        /// <summary>
        /// Check the minimal version given a com object guid.       
        /// </summary>
        /// <param name="sGuid">The guid of the object to be checked</param>
        /// <param name="major">Major version</param>
        /// <param name="minor">Minor version</param>
        /// <param name="build">Build version</param>
        /// <param name="rev">Revision version</param>
        /// <returns>True if the requested version or higher is pressent on the system.</returns>
        public bool CheckMinVersionGuid(string sGuid, int major, int minor, int build, int rev)
        {
            string spath;
            spath = GetGuidPath(sGuid);
            if (spath != string.Empty)
            {
                return (CheckMinVersion(spath, major, minor, build, rev));
            }
            return (false);
        }
        public string ExpandEnvironmentVariables(string sInputPath)
        {
            return Environment.ExpandEnvironmentVariables(sInputPath);
        }
        public bool HasInstallPrivileges()
        {
            //?
            System.AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
            //?
            System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
            System.Security.Principal.WindowsPrincipal wp = new System.Security.Principal.WindowsPrincipal(wi);
            if (wp.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                return true;
            else
                return false;
        }
    }
}

Open in new window

0
 
LVL 10

Assisted Solution

by:Jini Jose
Jini Jose earned 250 total points
ID: 33549226
if you have the solution file with you, you can open it in notepad to see the IDE version,

Microsoft Visual Studio Solution File, Format Version 10.00

if you have the project file open it in note pad.. you can see the .net version there

<Project ToolsVersion="3.5" DefaultTargets="Build"

<ProductVersion>9.0.21022</ProductVersion>


0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question