Solved

vertion of C#.net program

Posted on 2010-08-28
2
265 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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

708 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now