Powered by GeSHi

Source code for upcase.cs

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

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