Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the version of the .NET Framework being targeted? [duplicate]

Tags:

c#

.net

How can i get the version of the .NET Framework i am targeting, rather than the version of the .NET framework the app is currently running under?

For example, if the application targets .NET Framework 4.5, i would need to know that i am targeting .NET Framework 4.5.

For example, checking System.Environment.Version:

  • when targeting .NET Framework 4: 4.0.30319.18502
  • when targeting .NET Framework 4.5: 4.0.30319.18502

So that doesn't work.

The real goal is to try to work around the lack of compiler defines in .NET.

like image 845
Ian Boyd Avatar asked Sep 30 '13 14:09

Ian Boyd


People also ask

How do I know my target framework version?

To verify the change, on the menu bar, select Project > Properties to open your project Property Pages dialog box. In the dialog box, select the Configuration Properties > General property page. Verify that . NET Target Framework Version shows the new Framework version.


2 Answers

That's simple - check the TargetFrameworkAttribute:

var targetFrameworkAttribute = Assembly.GetExecutingAssembly()
    .GetCustomAttributes(typeof(System.Runtime.Versioning.TargetFrameworkAttribute), false)
    .SingleOrDefault();
like image 188
Sriram Sakthivel Avatar answered Nov 04 '22 02:11

Sriram Sakthivel


What prevents you from using an ordinary /define?

csc /define:NET45 /optimize /out:MyProgram.exe *.cs

with

using System;
public class Test 
{
    public static void Main() 
    {
        #if (NET45) 
            Console.WriteLine("NET45 targeted");
        #else
            Console.WriteLine("NET45 not targeted");
        #endif
    }
}
like image 21
Robert Harvey Avatar answered Nov 04 '22 02:11

Robert Harvey