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
  23. Send keystrokes to the active window
  24. Get window handle by its name/title

    Manage other program windows with P/Invoke

  25. Check if a window is minimized
  26. Get a window's size and position
  27. Move and resize a window
  28. Maximize, minimize or restore a window
  29. WindowState enumeration for ShowWindow and ShowWindowAsync functions
  30. Bring a window to the foreground

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; Skip( ) requires Linq
  2. string[] arguments = System.Environment.GetCommandLineArgs( ).Skip( 1 ).ToArray( ); // arguments in array
  3. string allarguments = string.Join( " ", arguments ); // arguments in single line
  4. string commandline = System.Environment.CommandLine; // entire command 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( 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 = 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 = 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 = 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 ) < 0 )
  6. 		{
  7. 			return earliest;
  8. 		}
  9. 		if ( System.DateTime.Compare( value, latest ) > 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 ( !string.IsNullOrWhiteSpace( domain ) )
  5. {
  6. 	query += 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( 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. }

 

23. Send keystrokes to the active window

  1. // For more details, including codes for special keys, see:
  2. // https://docs.microsoft.com/dotnet/api/system.windows.forms.sendkeys.send
  3. System.Windows.Forms.SendKeys.SendWait( string keys );

 

24. Get window handle by its name/title

  1. // Source: https://stackoverflow.com/a/13547659
  2. public static IntPtr WinGetHandle( string wName )
  3. {
  4. 	IntPtr hWnd = IntPtr.Zero;
  5. 	foreach ( Process pList in Process.GetProcesses( ) )
  6. 	{
  7. 		if ( pList.MainWindowTitle.Contains( wName ) )
  8. 		{
  9. 			hWnd = pList.MainWindowHandle;
  10. 		}
  11. 	}
  12. 	return hWnd; // Should contain the handle but may be zero if the title doesn't match
  13. }
  14.  

 

Manage other program windows with P/Invoke

The following code snippets use unmanaged code to manipulate other programs' windows by their window handle (see previous item).

For more details search for these functions on PInvoke.net.

Don't forget to include using System.Runtime.InteropServices; in your code.

25. Check if a window is minimized

  1. [DllImport( "user32.dll" )]
  2. [return: MarshalAs( UnmanagedType.Bool )]
  3. static extern bool IsIconic( IntPtr hWnd ); // true if window is minimized

 

26. Get a window's size and position

  1. [DllImport( "user32.dll", SetLastError = true )]
  2. [return: MarshalAs( UnmanagedType.Bool )]
  3. static extern bool GetWindowRect( IntPtr hWnd, ref RECT lpRect ); // RECT lpRect must be initialized before calling this function
  4.  
  5. [StructLayout( LayoutKind.Sequential )]
  6. public struct RECT
  7. {
  8. 	public int Left;
  9. 	public int Top;
  10. 	public int Right;
  11. 	public int Bottom;
  12. }

 

27. Move and resize a window

  1. [DllImport( "user32.dll" )]
  2. public static extern bool MoveWindow( IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint );

 

28. Maximize, minimize, hide or restore a window

  1. private const int SW_HIDE = 0;
  2. private const int SW_SHOWNORMAL = 1;
  3. private const int SW_SHOWMINIMIZED = 2;
  4. private const int SW_SHOWMAXIMIZED = 3;
  5.  
  6. [DllImport( "user32.dll" )]
  7. private static extern bool ShowWindow( IntPtr hWnd, int nCmdShow ); // Use one of the constants for nCmdShow to maximize, minimize or restore the window
  8.  
  9. [DllImport( "user32.dll" )]
  10. private static extern bool ShowWindowAsync( IntPtr hWnd, int nCmdShow ); // Same function but asynchronous

 

29. WindowState enumeration for ShowWindow and ShowWindowAsync functions

  1. // Instead of the separate constants for the ShowWindow and ShowWindowAsync functions you can use an enumeration.
  2. // Source: http://pinvoke.net/default.aspx/user32/ShowState.html
  3. public enum ShowState
  4. {
  5. 	SW_HIDE = 0,
  6. 	SW_SHOWNORMAL = 1,
  7. 	SW_NORMAL = 1,
  8. 	SW_SHOWMINIMIZED = 2,
  9. 	SW_SHOWMAXIMIZED = 3,
  10. 	SW_MAXIMIZE = 3,
  11. 	SW_SHOWNOACTIVATE = 4,
  12. 	SW_SHOW = 5,
  13. 	SW_MINIMIZE = 6,
  14. 	SW_SHOWMINNOACTIVE = 7,
  15. 	SW_SHOWNA = 8,
  16. 	SW_RESTORE = 9,
  17. 	SW_SHOWDEFAULT = 10,
  18. 	SW_FORCEMINIMIZE = 11,
  19. 	SW_MAX = 11
  20. }

 

30. Bring a window to the foreground

  1. // Will not immediately change the foreground window while another window receives input
  2. [DllImport( "user32.dll" )]
  3. public static extern bool SetForegroundWindow( IntPtr hWnd );

 


page last uploaded: 2021-01-27, 16:12