Rob van der Woude's Scripting Pages
Powered by GeSHi

C# Code Snippets

The following collection of C# code snippets assumes .NET Framework 4.0 is installed.
Check the code comments if later versions of the .NET Framework are required.

  1. Get the program's path
  2. Get the program's version
  3. Get the program's class and namespace
  4. Get the program's command line arguments
  5. Get the program's required .NET Framework version
  6. List installed .NET Framework versions
  7. Get the highest installed .NET Framework version
  8. Restart the program
  9. Restart the program with elevated privileges
  10. Wait
  11. Read redirected standard input
  12. Read text from clipboard
  13. HTML escape text
  14. Create a new temporary file
  15. Take a screenshot
  16. Case insensitive List.Contains extension method
  17. DateTime.LimitToRange( earliest, latest ), float.LimitToRange( min, max ) and int.LimitToRange( min, max ) extension methods
  18. Font.IsFixedPitch and FontFamily.IsFixedPitch extension methods
  19. Get today's Julian date
  20. Read text from a file on the web
  21. Search the web with Google
  22. Dynamically generate icons

1. Get the program's path

  1. string programpath = new System.Uri( System.Reflection.Assembly.GetExecutingAssembly( ).CodeBase ).LocalPath;
  2. // Or for Windows Forms:
  3. // string programpath = System.Windows.Forms.Application.ExecutablePath;

 

2. Get the program's version

  1. string progver = System.Reflection.Assembly.GetExecutingAssembly( ).GetName( ).Version.ToString( );

 

3. Get the program's class and namespace

  1. Console.WriteLine( "Class     : {0}", System.Reflection.Assembly.GetEntryAssembly( ).EntryPoint.DeclaringType.Name );
  2. Console.WriteLine( "Namespace : {0}", System.Reflection.Assembly.GetEntryAssembly( ).EntryPoint.DeclaringType.Namespace );

 

4. Get the program's command line arguments

  1. // Skip( 1 ) removes the first argument, i.e. the program name
  2. string[] arguments = System.Environment.GetCommandLineArgs( ).Skip( 1 ).ToArray( ); // requires Linq
  3. string allarguments = System.String.Join( " ", arguments ); // single line

 

5. Get the program's required .NET Framework version

  1. // Get the required .NET Framework version
  2. // By Fernando Gonzalez Sanchez on StackOverflow.com
  3. // https://stackoverflow.com/a/18623516
  4. object[] list = System.Reflection.Assembly.GetExecutingAssembly( ).GetCustomAttributes( true );
  5. var attribute = list.OfType<System.Runtime.Versioning.TargetFrameworkAttribute>( ).First( ); // requires Linq
  6. string frameworkname = attribute.FrameworkName;
  7. string frameworkdisplayname = attribute.FrameworkDisplayName;

 

6. List installed .NET Framework versions

  1. // Source of this code snippet:
  2. // https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed
  3.  
  4. // Opens the registry key for the .NET Framework entry.
  5. using ( Microsoft.Win32.RegistryKey ndpKey =
  6. 	Microsoft.Win32.RegistryKey.OpenRemoteBaseKey( Microsoft.Win32.RegistryHive.LocalMachine, "" )
  7. 	.OpenSubKey( @"SOFTWARE\Microsoft\NET Framework Setup\NDP\" ) )
  8. {
  9. 	// As an alternative, if you know the computers you will query are running .NET Framework 4.5 or later, you can use:
  10. 	// using ( Microsoft.Win32.RegistryKey ndpKey =
  11. 	// 	Microsoft.Win32.RegistryKey.OpenBaseKey( Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry32 )
  12. 	// 	.OpenSubKey( @"SOFTWARE\Microsoft\NET Framework Setup\NDP\" ) )
  13. 	foreach ( string versionKeyName in ndpKey.GetSubKeyNames( ) )
  14. 	{
  15. 		if ( versionKeyName.StartsWith( "v" ) )
  16. 		{
  17. 			Microsoft.Win32.RegistryKey versionKey = ndpKey.OpenSubKey( versionKeyName );
  18. 			string name = (string) versionKey.GetValue( "Version", "" );
  19. 			string sp = versionKey.GetValue( "SP", "" ).ToString( );
  20. 			string install = versionKey.GetValue( "Install", "" ).ToString( );
  21. 			if ( install == "" ) //no install info, must be later.
  22. 			{
  23. 				System.Console.WriteLine( versionKeyName + "  " + name );
  24. 			}
  25. 			else
  26. 			{
  27. 				if ( sp != "" && install == "1" )
  28. 				{
  29. 					System.Console.WriteLine( versionKeyName + "  " + name + "  SP" + sp );
  30. 				}
  31. 			}
  32. 			if ( name != "" )
  33. 			{
  34. 				continue;
  35. 			}
  36. 			foreach ( string subKeyName in versionKey.GetSubKeyNames( ) )
  37. 			{
  38. 				Microsoft.Win32.RegistryKey subKey = versionKey.OpenSubKey( subKeyName );
  39. 				name = (string) subKey.GetValue( "Version", "" );
  40. 				if ( name != "" )
  41. 				{
  42. 					sp = subKey.GetValue( "SP", "" ).ToString( );
  43. 				}
  44. 				install = subKey.GetValue( "Install", "" ).ToString( );
  45. 				if ( install == "" ) //no install info, must be later.
  46. 				{
  47. 					System.Console.WriteLine( versionKeyName + "  " + name );
  48. 				}
  49. 				else
  50. 				{
  51. 					if ( sp != "" && install == "1" )
  52. 					{
  53. 						System.Console.WriteLine( "  " + subKeyName + "  " + name + "  SP" + sp );
  54. 					}
  55. 					else if ( install == "1" )
  56. 					{
  57. 						System.Console.WriteLine( "  " + subKeyName + "  " + name );
  58. 					}
  59. 				}
  60. 			}
  61. 		}
  62. 	}
  63. }

 

7. Get the highest installed .NET Framework version

  1. int rc = 0; // default return code if no .NET Framework is found
  2. System.Collections.Generic.List<string> installedversions = new System.Collections.Generic.List<string>( ); // list of all versions installed
  3. int[] highestversion = new int[] { 0, 0, 0, 0 }; // helper variable to determine which string represents the highest version
  4. // Get the list of installed .NET Framework versions from the registry, by Microsoft:
  5. // https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed
  6. using ( Microsoft.Win32.RegistryKey ndpKey =
  7. 	Microsoft.Win32.RegistryKey.OpenRemoteBaseKey( Microsoft.Win32.RegistryHive.LocalMachine, "" )
  8. 	.OpenSubKey( @"SOFTWARE\Microsoft\NET Framework Setup\NDP\" ) )
  9. {
  10. 	foreach ( string versionKeyName in ndpKey.GetSubKeyNames( ) )
  11. 	{
  12. 		if ( versionKeyName.StartsWith( "v" ) )
  13. 		{
  14. 			Microsoft.Win32.RegistryKey versionKey = ndpKey.OpenSubKey( versionKeyName );
  15. 			string name = (string) versionKey.GetValue( "Version", "" );
  16. 			if ( name == "" )
  17. 			{
  18. 				foreach ( string subKeyName in versionKey.GetSubKeyNames( ) )
  19. 				{
  20. 					Microsoft.Win32.RegistryKey subKey = versionKey.OpenSubKey( subKeyName );
  21. 					name = (string) subKey.GetValue( "Version", "" );
  22. 					if ( name != "" )
  23. 					{
  24. 						installedversions.Add( name );
  25. 					}
  26. 				}
  27. 			}
  28. 			else
  29. 			{
  30. 				installedversions.Add( name );
  31. 			}
  32. 		}
  33. 	}
  34. }
  35. // Determine the highest version
  36. foreach ( string version in installedversions )
  37. {
  38. 	int[] version2 = version.Split( ".".ToCharArray( ) ).Select( x => System.Convert.ToInt32( x ) ).ToArray( );
  39. 	int minlength = System.Math.Min( version.Length, version2.Length );
  40. 	for ( int i = 0; i < minlength; i++ )
  41. 	{
  42. 		if ( highestversion[i] < System.Convert.ToInt32( version2[i] ) )
  43. 		{
  44. 			highestversion = version2;
  45. 			break;
  46. 		}
  47. 	}
  48. }
  49. // Write version string to screen
  50. System.Console.WriteLine( System.String.Join( ".", highestversion.Select( x => x.ToString( ) ).ToArray( ) ) ); // requires System.Linq
  51. // Return code is based on first 2 digits of highest version
  52. rc = 100 * highestversion[0] + highestversion[1];
  53. return rc;

 

8. Restart the program

  1. string programpath = new System.Uri( System.Reflection.Assembly.GetExecutingAssembly( ).CodeBase ).LocalPath;
  2. // Or for Windows Forms:
  3. // string programpath = System.Windows.Forms.Application.ExecutablePath;
  4. string[] arguments = System.Environment.GetCommandLineArgs( ).Skip( 1 ).ToArray( ); // requires Linq
  5. System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo( );
  6. startinfo.FileName = programpath;
  7. startinfo.UseShellExecute = true;
  8. startinfo.Arguments = System.String.Join( " ", arguments );
  9. System.Diagnostics.Process.Start( startinfo );
  10. System.Environment.Exit( 0 ); // return code 0, change if required
  11. // Or for Windows Forms:
  12. // System.Windows.Forms.Application.Exit( );
  13.  

 

9. Restart the program with elevated privileges

  1. string programpath = new System.Uri( System.Reflection.Assembly.GetExecutingAssembly( ).CodeBase ).LocalPath;
  2. // Or for Windows Forms:
  3. // string programpath = System.Windows.Forms.Application.ExecutablePath;
  4. string[] arguments = System.Environment.GetCommandLineArgs( ).Skip( 1 ).ToArray( ); // requires Linq
  5. System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo( );
  6. startinfo.FileName = programpath;
  7. startinfo.UseShellExecute = true;
  8. startinfo.Verb = "runas";
  9. startinfo.Arguments = String.Join( " ", arguments );
  10. System.Diagnostics.Process.Start( startinfo );
  11. System.Environment.Exit( 0 ); // return code 0, change if required
  12. // Or for Windows Forms:
  13. // System.Windows.Forms.Application.Exit( );
  14.  

 

10. Wait

  1. System.Threading.Thread.Sleep( 5000 ); // wait 5 seconds (5000 milliseconds)

 

11. Read redirected standard input

  1. string input = System.String.Empty;
  2. if ( System.Console.IsInputRedirected ) // requires .NET Framework 4.5
  3. {
  4. 	System.Console.OpenStandardInput( );
  5. 	input = System.Console.In.ReadToEnd( );
  6. }

 

12. Read text from clipboard

  1. string cliptext = System.String.Empty;
  2. if ( System.Windows.Forms.Clipboard.ContainsText( ) )
  3. {
  4. 	clipText = System.Windows.Forms.Clipboard.GetText( );
  5. }

 

13. HTML escape text

  1. string unescapedtext = "4 > 3";
  2. string escapedtext = System.Net.WebUtility.HtmlEncode( unescapedtext );

 

14. Create a new temporary file

  1. // This will create a new temporary file and return its path
  2. string newtempfile = System.IO.Path.GetTempFileName( );

 

15. Take a screenshot

  1. // Take a screenshot
  2. // By Ali Hamdar (http://alihamdar.com/)
  3. // http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/79efecc4-fa6d-4078-afe4-bb1379bb968b
  4.  
  5. // Default values for full screen
  6. int width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
  7. int height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
  8. int top = 0;
  9. int left = 0;
  10.  
  11. System.Drawing.Bitmap printscreen = new System.Drawing.Bitmap( width, height );
  12. System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage( printscreen as Image );
  13. graphics.CopyFromScreen( top, left, 0, 0, printscreen.Size );
  14. printscreen.Save( outputfile, imagetype );

 

16. Case insensitive List.Contains( key ) extension method

  1. public static class ExtensionMethods
  2. {
  3. 	public static bool ContainsCI( this System.Collections.Generic.List<string> value, string key )
  4. 	{
  5. 		return value.Any( k => k.Equals( key, System.StringComparison.OrdinalIgnoreCase ) ); // requires Linq
  6. 	}
  7. }

 

17. DateTime.LimitToRange( earliest, latest ), float.LimitToRange( min, max ) and int.LimitToRange( min, max ) extension methods

  1. public static class ExtensionMethods
  2. {
  3. 	public static System.DateTime LimitToRange( this System.DateTime value, System.DateTime earliest, System.DateTime latest )
  4. 	{
  5. 		if ( System.DateTime.Compare( value, earliest ) &lt; 0 )
  6. 		{
  7. 			return earliest;
  8. 		}
  9. 		if ( System.DateTime.Compare( value, latest )&gt; 0 )
  10. 		{
  11. 			return latest;
  12. 		}
  13. 		return value;
  14. 	}
  15.  
  16. 	public static float LimitToRange( this float value, float inclusiveMinimum, float inclusiveMaximum )
  17. 	{
  18. 		if ( value < inclusiveMinimum )
  19. 		{
  20. 			return inclusiveMinimum;
  21. 		}
  22. 		if ( value > inclusiveMaximum )
  23. 		{
  24. 			return inclusiveMaximum;
  25. 		}
  26. 		return value;
  27. 	}
  28.  
  29. 	// Extension by "dtb" on StackOverflow.com:
  30. 	// https://stackoverflow.com/a/3176628
  31. 	public static int LimitToRange( this int value, int inclusiveMinimum, int inclusiveMaximum )
  32. 	{
  33. 		if ( value < inclusiveMinimum )
  34. 		{
  35. 			return inclusiveMinimum;
  36. 		}
  37. 		if ( value > inclusiveMaximum )
  38. 		{
  39. 			return inclusiveMaximum;
  40. 		}
  41. 		return value;
  42. 	}
  43. }

 

18. Font.IsFixedPitch and FontFamily.IsFixedPitch extension methods

  1. public static class ExtensionMethods
  2. {
  3. 	public static bool IsFixedPitch( this System.Drawing.FontFamily value )
  4. 	{
  5. 		System.Drawing.Font font = new System.Drawing.Font( value, 12, System.Drawing.FontStyle.Regular );
  6. 		return ( System.Windows.Forms.TextRenderer.MeasureText( "WWWWW", font ) == System.Windows.Forms.TextRenderer.MeasureText( "IIIII", font ) );
  7. 	}
  8.  
  9. 	public static bool IsFixedPitch( this System.Drawing.Font value )
  10. 	{
  11. 		// Inspired by a tip from Hans passant
  12. 		// https://stackoverflow.com/q/21965321
  13. 		return ( System.Windows.Forms.TextRenderer.MeasureText( "WWWWW", value ) == System.Windows.Forms.TextRenderer.MeasureText( "IIIII", value ) );
  14. 	}
  15. }

 

19. Get today's Julian date

  1. // Code to convert today's date to Julian date by David Yaw
  2. // https://stackoverflow.com/a/5254812
  3. double juliandate = System.DateTime.Today.ToOADate( ) + 2415018.5;

 

20. Read text from a file on the web

  1. string url = "https://www.example.com/example.txt"
  2. // The next couple of ServicePointManager lines are required for secure connections only
  3. System.Net.ServicePointManager.Expect100Continue = true;
  4. System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12;
  5. System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Ssl3;
  6. System.Net.WebClient webclient = new System.Net.WebClient( );
  7. string text = webclient.DownloadString( url );
  8. webclient.Dispose( );

 

21. Search the web with Google

  1. // This will open search results from Google in your default browser
  2. string query = System.Uri.EscapeDataString( "whatever it is I'm looking for" );
  3. string domain = "microsoft.com"; // search only on this domain
  4. if ( !System.String.IsNullOrWhiteSpace( domain ) )
  5. {
  6. 	query += System.String.Format( "+site:{0}", domain );
  7. }
  8. string url = String.Format( "https://www.google.com/search?q={0}&btnI=745&pws=0", query );
  9. System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo( url );
  10. System.Diagnostics.Process.Start( startinfo );

 

22. Dynamically generate icons

  1. // Dynamically generate icons; based on code by Joshua Flanagan on CodeProject.com
  2. // https://www.codeproject.com/Articles/7122/Dynamically-Generating-Icons-safely
  3. // This code will create an icon, draw a circle and fill it with backgroundcolor, and place some text (not too long) in the center
  4. public System.Drawing.Icon CreateIcon( System.String text, System.Drawing.Font font, System.Drawing.Brush foregroundcolor, System.Drawing.Brush backgroundcolor )
  5. {
  6. 	System.Drawing.Icon icon = null;
  7. 	System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap( 16, 16 );
  8. 	using ( System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage( bitmap ) )
  9. 	{
  10. 		graphic.FillEllipse( backgroundcolor, 0, 0, 16, 16 ); // Create circle and fill it with  background color
  11. 		System.Drawing.SizeF textsize = graphic.MeasureString( text, font ); // Determine the size and position of the text
  12. 		System.Single x = System.Convert.ToSingle( System.Math.Floor( ( bitmap.Width - textsize.Width ) / 2 ) );
  13. 		System.Single y = System.Convert.ToSingle( System.Math.Ceiling( ( bitmap.Height - textsize.Height ) / 2 ) );
  14. 		graphic.DrawString( text, font, foregroundcolor, x, y, System.Drawing.StringFormat.GenericDefault ); // Generate an image of the text
  15. 		icon = System.Drawing.Icon.FromHandle( bitmap.GetHicon( ) );
  16. 	}
  17. 	return icon;
  18. }

 


page last uploaded: 2019-02-21, 10:00