Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for upcase.cs

(view source code of upcase.cs as plain text)

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6.  
  7.  
  8. namespace RobvanderWoude
  9. {
  10. 	class UpCase
  11. 	{
  12. 		public static string progver = "2.01";
  13.  
  14.  
  15. 		static int Main( string[] args )
  16. 		{
  17. 			string filespec = string.Empty;
  18. 			bool isredirected = ConsoleEx.InputRedirected;
  19. 			bool verbose = false;
  20.  
  21. 			#region Command Line Parsing
  22.  
  23. 			if ( isredirected )
  24. 			{
  25. 				// No command line arguments in case of redirected input
  26. 				if ( args.Length > 0 )
  27. 				{
  28. 					return ShowHelp( );
  29. 				}
  30. 			}
  31. 			else
  32. 			{
  33. 				switch ( args.Length )
  34. 				{
  35. 					case 1:
  36. 						filespec = args[0].Trim( '"' );
  37. 						break;
  38. 					case 2:
  39. 						filespec = args[0].Trim( '"' );
  40. 						if ( args[1].Substring( 0, 2 ).ToUpper( ) == "/V" )
  41. 						{
  42. 							verbose = true;
  43. 						}
  44. 						else
  45. 						{
  46. 							return ShowHelp( "Invalid command line argument \"{0}\"", args[1] );
  47. 						}
  48. 						break;
  49. 					default:
  50. 						return ShowHelp( );
  51. 				}
  52. 				if ( string.IsNullOrWhiteSpace( filespec ) || filespec == "/?" )
  53. 				{
  54. 					return ShowHelp( );
  55. 				}
  56. 				if ( filespec.IndexOfAny( "/?".ToCharArray( ) ) != -1 )
  57. 				{
  58. 					return ShowHelp( "Invalid file specification: \"{0}\"", filespec );
  59. 				}
  60. 			}
  61.  
  62. 			#endregion Command Line Parsing
  63.  
  64.  
  65. 			if ( isredirected ) // Redirected input
  66. 			{
  67. 				#region Convert redirected input to upper case
  68.  
  69. 				Console.OpenStandardInput( );
  70. 				string input = Console.In.ReadToEnd( );
  71. 				Console.OpenStandardOutput( );
  72. 				string output = input.ToUpper( );
  73. 				Console.Out.Write( output );
  74. 				return 0;
  75.  
  76. 				#endregion Convert redirected input to upper case
  77. 			}
  78. 			else
  79. 			{
  80. 				#region Rename files to upper case
  81.  
  82. 				string dir = string.Empty;
  83. 				char[] trailingbackslash = "\\".ToCharArray( );
  84. 				char[] locaseletters = "abcdefghijklmnopqrstuvwxyz".ToCharArray( );
  85.  
  86. 				try
  87. 				{
  88. 					// Check if the directory exists
  89. 					try
  90. 					{
  91. 						dir = Path.GetDirectoryName( filespec );
  92. 						if ( string.IsNullOrWhiteSpace( dir ) )
  93. 						{
  94. 							dir = Directory.GetCurrentDirectory( );
  95. 						}
  96. 						if ( !Directory.Exists( dir ) )
  97. 						{
  98. 							return ShowHelp( "Directory not found: \"{0}\"", dir );
  99. 						}
  100. 						dir = dir.TrimEnd( trailingbackslash ) + "\\";
  101. 					}
  102. 					catch ( ArgumentException )
  103. 					{
  104. 						return ShowHelp( "Parent directory not found" );
  105. 					}
  106.  
  107. 					// Extract the FILE specification (removing the path)
  108. 					string filenames = filespec.Substring( filespec.LastIndexOf( "\\" ) + 1 );
  109. 					// Enumerate the files
  110. 					string[] files = Directory.EnumerateFiles( dir, filenames ).ToArray<string>( );
  111. 					int count = 0;
  112. 					foreach ( string file in files )
  113. 					{
  114. 						if ( File.Exists( file ) )
  115. 						{
  116. 							string filename = Path.GetFileName( file );
  117. 							if ( filename.IndexOfAny( locaseletters ) > -1 )
  118. 							{
  119. 								count++;
  120. 								string newfilename = Path.Combine( dir, filename.ToUpperInvariant( ) );
  121. 								try
  122. 								{
  123. 									File.Move( file, newfilename );
  124. 								}
  125. 								catch ( Exception e )
  126. 								{
  127. 									Console.Error.WriteLine( "{0}: {1}", filename, e.Message );
  128. 								}
  129. 							}
  130. 						}
  131. 					}
  132. 					if ( verbose )
  133. 					{
  134. 						Console.WriteLine( "{0} matching file{1} renamed", ( count == 0 ? "No" : count.ToString( ) ), ( count == 1 ? string.Empty : "s" ) );
  135. 					}
  136. 					return count;
  137. 				}
  138. 				catch ( Exception e )
  139. 				{
  140. 					return ShowHelp( e.Message );
  141. 				}
  142.  
  143. 				#endregion Rename files to upper case
  144. 			}
  145. 		}
  146.  
  147.  
  148. 		#region Redirection Detection
  149.  
  150. 		// Code to detect redirection by Hans Passant on StackOverflow.com
  151. 		// http://stackoverflow.com/questions/3453220/how-to-detect-if-console-in-stdin-has-been-redirected
  152. 		public static class ConsoleEx
  153. 		{
  154. 			public static bool OutputRedirected
  155. 			{
  156. 				get
  157. 				{
  158. 					return FileType.Char != GetFileType( GetStdHandle( StdHandle.Stdout ) );
  159. 				}
  160. 			}
  161.  
  162. 			public static bool InputRedirected
  163. 			{
  164. 				get
  165. 				{
  166. 					return FileType.Char != GetFileType( GetStdHandle( StdHandle.Stdin ) );
  167. 				}
  168. 			}
  169.  
  170. 			public static bool ErrorRedirected
  171. 			{
  172. 				get
  173. 				{
  174. 					return FileType.Char != GetFileType( GetStdHandle( StdHandle.Stderr ) );
  175. 				}
  176. 			}
  177.  
  178. 			// P/Invoke:
  179. 			private enum FileType { Unknown, Disk, Char, Pipe };
  180. 			private enum StdHandle { Stdin = -10, Stdout = -11, Stderr = -12 };
  181.  
  182. 			[DllImport( "kernel32.dll" )]
  183. 			private static extern FileType GetFileType( IntPtr hdl );
  184.  
  185. 			[DllImport( "kernel32.dll" )]
  186. 			private static extern IntPtr GetStdHandle( StdHandle std );
  187. 		}
  188.  
  189. 		#endregion Redirection Detection
  190.  
  191.  
  192. 		#region Error handling
  193.  
  194. 		public static int ShowHelp( params string[] errmsg )
  195. 		{
  196. 			/*
  197. 			UpCase.exe,  Version 2.01
  198. 			Either rename specified files or render redirected input to all upper case
  199.  
  200. 			Usage:    UpCase.exe  filespec  [ /Verbose ]
  201.  
  202. 			or:       some_command  |  UpCase.exe
  203.  
  204. 			Where:    filespec       the file(s) to be renamed        (wildcards allowed)
  205. 			          some_command   a command whose output will be rendered to upper case
  206. 			          /Verbose       displays number of files renamed (requires filespec)
  207.  
  208. 			Notes:    Use doublequotes if filespec contains non-alphnumeric characters.
  209. 			          Return code (\"ErrorLevel\") equals the number of renamed files.
  210. 			          Switch may be abbreviated, e.g. /V instead of /Verbose.
  211.  
  212. 			Check for redirection by Hans Passant on StackOverflow.com
  213. 			/questions/3453220/how-to-detect-if-console-in-stdin-has-been-redirected
  214.  
  215. 			Written by Rob van der Woude
  216. 			http://www.robvanderwoude.com
  217. 			*/
  218.  
  219. 			if ( errmsg.Length > 0 )
  220. 			{
  221. 				List<string> errargs = new List<string>( errmsg );
  222. 				errargs.RemoveAt( 0 );
  223. 				Console.Error.WriteLine( );
  224. 				Console.ForegroundColor = ConsoleColor.Red;
  225. 				Console.Error.Write( "ERROR:\t" );
  226. 				Console.ForegroundColor = ConsoleColor.White;
  227. 				Console.Error.WriteLine( errmsg[0], errargs.ToArray( ) );
  228. 				Console.ResetColor( );
  229. 			}
  230.  
  231. 			Console.Error.WriteLine( );
  232.  
  233. 			Console.Error.WriteLine( "UpCase.exe,  Version {0}", progver );
  234.  
  235. 			Console.Error.WriteLine( "Either rename specified files or render redirected input to all upper case" );
  236.  
  237. 			Console.Error.WriteLine( );
  238.  
  239. 			Console.Error.Write( "Usage:    " );
  240. 			Console.ForegroundColor = ConsoleColor.White;
  241. 			Console.Error.WriteLine( "UpCase.exe  filespec  [ /Verbose ]" );
  242. 			Console.ResetColor( );
  243.  
  244. 			Console.Error.WriteLine( );
  245.  
  246. 			Console.Error.Write( "or:       " );
  247. 			Console.ForegroundColor = ConsoleColor.White;
  248. 			Console.Error.WriteLine( "some_command  |  UpCase.exe" );
  249. 			Console.ResetColor( );
  250.  
  251. 			Console.Error.WriteLine( );
  252.  
  253. 			Console.Error.Write( "Where:    " );
  254. 			Console.ForegroundColor = ConsoleColor.White;
  255. 			Console.Error.Write( "filespec" );
  256. 			Console.ResetColor( );
  257. 			Console.Error.WriteLine( "       the file(s) to be renamed        (wildcards allowed)" );
  258.  
  259. 			Console.ForegroundColor = ConsoleColor.White;
  260. 			Console.Error.Write( "          some_command" );
  261. 			Console.ResetColor( );
  262. 			Console.Error.WriteLine( "   a command whose output will be rendered to upper case" );
  263.  
  264. 			Console.ForegroundColor = ConsoleColor.White;
  265. 			Console.Error.Write( "          /V" );
  266. 			Console.ResetColor( );
  267. 			Console.Error.WriteLine( "erbose       displays number of files renamed (requires filespec)" );
  268.  
  269. 			Console.Error.WriteLine( );
  270.  
  271. 			Console.Error.WriteLine( "Notes:    Use doublequotes if filespec contains non-alphnumeric characters." );
  272.  
  273. 			Console.Error.WriteLine( "          Return code (\"ErrorLevel\") equals the number of renamed files." );
  274.  
  275. 			Console.Error.Write( "          Switch may be abbreviated, e.g. " );
  276. 			Console.ForegroundColor = ConsoleColor.White;
  277. 			Console.Error.Write( "/V" );
  278. 			Console.ResetColor( );
  279. 			Console.Error.Write( " instead of " );
  280. 			Console.ForegroundColor = ConsoleColor.White;
  281. 			Console.Error.Write( "/V" );
  282. 			Console.ResetColor( );
  283. 			Console.Error.WriteLine( "erbose." );
  284.  
  285. 			Console.Error.WriteLine( );
  286.  
  287.  
  288. 			Console.Error.Write( "Check for redirection by Hans Passant on " );
  289. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  290. 			Console.Error.WriteLine( "StackOverflow.com" );
  291.  
  292. 			Console.Error.WriteLine( "/questions/3453220/how-to-detect-if-console-in-stdin-has-been-redirected" );
  293. 			Console.ResetColor( );
  294.  
  295. 			Console.Error.WriteLine( );
  296.  
  297. 			Console.Error.WriteLine( "Written by Rob van der Woude" );
  298.  
  299. 			Console.Error.WriteLine( "http://www.robvanderwoude.com" );
  300.  
  301. 			return 0;
  302. 		}
  303.  
  304. 		#endregion Error handling
  305. 	}
  306. }
  307.  

page last uploaded: 2015-12-04, 16:51