Solved

vertion of C#.net program

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…

911 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

20 Experts available now in Live!

Get 1:1 Help Now