Powered by GeSHi

Source code for wgetlite.cs

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

  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text;
  5. using System.Threading;
  6.  
  7. namespace RobvanderWoude
  8. {
  9. 	class WGetLite
  10. 	{
  11. 		private static ManualResetEvent allDone = new ManualResetEvent( false );
  12.  
  13. 		static int Main( string[] args )
  14. 		{
  15. 			string url = string.Empty;
  16. 			string enc = "ASCII";
  17. 			string outputFile = string.Empty;
  18. 			int statusCode = 0;
  19. 			bool save = false;
  20. 			bool overwrite = false;
  21. 			bool show = true;
  22.  
  23. 			#region Command Line Parsing
  24.  
  25. 			// Custom error message
  26. 			string msgInvalid = "Invalid command line argument" + ( ( args.Length == 1 ) ? string.Empty : "(s)" );
  27.  
  28. 			// No command line arguments? Display help
  29. 			if ( args.Length == 0 )
  30. 			{
  31. 				return WriteError( string.Empty );
  32. 			}
  33.  
  34. 			foreach ( string arg in args )
  35. 			{
  36. 				// Check switches first
  37. 				switch ( arg.ToLower( ).Substring( 0, 2 ) )
  38. 				{
  39. 					case "/?":
  40. 					case "-?":
  41. 					case "/h":
  42. 					case "-h":
  43. 						// Display help
  44. 						return WriteError( string.Empty );
  45. 					case "--":
  46. 						if ( arg.ToLower( ) == "--help" )
  47. 						{
  48. 							// Display help
  49. 							return WriteError( string.Empty );
  50. 						}
  51. 						else
  52. 						{
  53. 							// Display error message
  54. 							return WriteError( msgInvalid );
  55. 						}
  56. 					case "/e":
  57. 						if ( arg.ToLower( ).StartsWith( "/e:" ) || arg.ToLower( ).StartsWith( "/encoding:" ) )
  58. 						{
  59. 							enc = arg.Substring( arg.IndexOf( ":" ) + 1 );
  60. 						}
  61. 						else
  62. 						{
  63. 							return WriteError( msgInvalid );
  64. 						}
  65. 						break;
  66. 					case "/o":
  67. 						overwrite = true;
  68. 						break;
  69. 					case "/r":
  70. 						show = false;
  71. 						break;
  72. 					case "/s":
  73. 						show = false;
  74. 						save = true;
  75. 						if ( arg.ToLower( ).StartsWith( "/s:" ) || arg.ToLower( ).StartsWith( "/save:" ) )
  76. 						{
  77. 							outputFile = arg.Substring( arg.IndexOf( ":" ) + 1 );
  78. 						}
  79. 						else
  80. 						{
  81. 							return WriteError( msgInvalid );
  82. 						}
  83. 						break;
  84. 					default:
  85. 						url = arg;
  86. 						break;
  87. 				}
  88. 			}
  89.  
  90. 			if ( string.IsNullOrEmpty( url ) )
  91. 			{
  92. 				return WriteError( "A URL must be specified" );
  93. 			}
  94.  
  95. 			if ( overwrite && !save )
  96. 			{
  97. 				return WriteError( "/Overwrite requires /Save." );
  98. 			}
  99.  
  100. 			if ( save )
  101. 			{
  102. 				if ( File.Exists( @outputFile ) )
  103. 				{
  104. 					if ( !overwrite )
  105. 					{
  106. 						return WriteError( "File already exists." );
  107. 					}
  108. 				}
  109. 			}
  110.  
  111. 			#endregion Command Line Parsing
  112.  
  113. 			try
  114. 			{
  115. 				statusCode = (int) GetResponse( url );
  116.  
  117. 				if ( save )
  118. 				{
  119. 					using ( StreamWriter outputStream = new StreamWriter( @outputFile ) )
  120. 					{
  121. 						if ( overwrite )
  122. 						{
  123. 							outputStream.Flush( );
  124. 						}
  125. 						outputStream.Write( Get( url, enc ) );
  126. 						outputStream.Close( );
  127. 					}
  128. 				}
  129. 				else if ( show )
  130. 				{
  131. 					Console.Write( Get( url, enc ) );
  132. 				}
  133.  
  134. 				return ( statusCode == 200 ? 0 : statusCode );
  135. 			}
  136. 			catch ( Exception e )
  137. 			{
  138. 				return WriteError( e.Message );
  139. 			}
  140. 		}
  141.  
  142.  
  143. 		public static HttpStatusCode GetResponse( string url )
  144. 		{
  145. 			// Returns the HTTP Status Code for the specified URL, or 0 on errors
  146. 			try
  147. 			{
  148. 				HttpWebRequest req = (HttpWebRequest) WebRequest.Create( url );
  149. 				req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
  150. 				req.AllowAutoRedirect = false;
  151. 				HttpWebResponse resp = (HttpWebResponse) req.GetResponse( );
  152. 				HttpStatusCode stat = resp.StatusCode;
  153. 				req.Abort( );
  154. 				return stat;
  155. 			}
  156. 			catch ( WebException e )
  157. 			{
  158. 				// Handle exceptions caused by the server response, e.g. 404
  159. 				try
  160. 				{
  161. 					HttpWebResponse httpResponse = (HttpWebResponse) e.Response;
  162. 					return httpResponse.StatusCode;
  163. 				}
  164. 				// Handle the "real" exceptions
  165. 				catch
  166. 				{
  167. 					WriteError( e.Message );
  168. 					return 0;
  169. 				}
  170. 			}
  171. 			catch ( Exception e )
  172. 			{
  173. 				WriteError( e.Message );
  174. 				return 0;
  175. 			}
  176. 		}
  177.  
  178.  
  179. 		// Get( ) based on blog post by Sugree Phatanapherom
  180. 		// http://www.howforge.com/how-to-implement-simple-wget-in-c
  181. 		private static string Get( string url, string encoding )
  182. 		{
  183. 			try
  184. 			{
  185. 				WebClient webClient = new WebClient( );
  186. 				byte[] response = webClient.DownloadData( url );
  187. 				switch ( encoding.ToUpper( ) )
  188. 				{
  189. 					case "A":
  190. 					case "ANSI":
  191. 					case "ASCII":
  192. 						return Encoding.ASCII.GetString( response );
  193. 					case "U":
  194. 					case "ULE":
  195. 					case "UNICODE":
  196. 					case "UNICODELE":
  197. 					case "UNICODE LE":
  198. 					case "UNICODE (LE)":
  199. 						return Encoding.Unicode.GetString( response );
  200. 					case "UB":
  201. 					case "UBE":
  202. 					case "UNICODEBE":
  203. 					case "UNICODE BE":
  204. 					case "UNICODE (BE)":
  205. 						return Encoding.BigEndianUnicode.GetString( response );
  206. 					case "U7":
  207. 					case "UTF7":
  208. 					case "UTF-7":
  209. 						return Encoding.UTF7.GetString( response );
  210. 					case "U8":
  211. 					case "UTF8":
  212. 					case "UTF-8":
  213. 						return Encoding.UTF8.GetString( response );
  214. 					case "U32":
  215. 					case "UTF32":
  216. 					case "UTF-32":
  217. 						return Encoding.UTF32.GetString( response );
  218. 					default:
  219. 						WriteError( "Invalid encoding" );
  220. 						return string.Empty;
  221. 				}
  222. 			}
  223. 			catch ( Exception e )
  224. 			{
  225. 				WriteError( e.Message );
  226. 				return string.Empty;
  227. 			}
  228. 		}
  229.  
  230. 		#region Error Handling
  231.  
  232. 		public static int WriteError( Exception e )
  233. 		{
  234. 			return WriteError( e == null ? null : e.Message );
  235. 		}
  236.  
  237. 		public static int WriteError( string errorMessage )
  238. 		{
  239. 			/*
  240. 			WGetLite,  Version 1.00
  241. 			Get web content (text only)
  242.  
  243. 			Usage:  WGETLITE  url  [ /Response | /Save:filename ]  [ /Encoding:encoding ]
  244.  
  245. 			Where:  /Response returns server response code only
  246. 					/Save     saves downloaded content to specified file
  247. 					/Encoding specifies encoding of url; accepted values are:
  248. 			                  ANSI, Unicode, Unicode (BE), UTF-7, UTF-8, UTF-32
  249.  
  250. 			Notes:  On errors the actual HTTP response code is returned as 'errorlevel'.
  251. 			        Usually specifying the encoding won't be necessary.
  252. 			        Switches may be abbreviated, e.g. /E:U8 instead of /Encoding:UTF-8.
  253. 			        Based on a blog post by Sugree Phatanapherom:
  254. 			        http://www.howforge.com/how-to-implement-simple-wget-in-c
  255.  
  256. 			Written by Rob van der Woude
  257. 			http://www.robvanderwoude.com
  258. 			*/
  259.  
  260. 			if ( string.IsNullOrEmpty( errorMessage ) == false )
  261. 			{
  262. 				Console.Error.WriteLine( );
  263. 				Console.ForegroundColor = ConsoleColor.Red;
  264. 				Console.Error.Write( "ERROR:  " );
  265. 				Console.ForegroundColor = ConsoleColor.White;
  266. 				Console.Error.WriteLine( errorMessage );
  267. 				Console.ResetColor( );
  268. 			}
  269. 			Console.Error.WriteLine( );
  270. 			Console.Error.WriteLine( "WGetLite,  Version 1.00" );
  271. 			Console.Error.WriteLine( "Get web content (text only)" );
  272. 			Console.Error.WriteLine( );
  273. 			Console.Error.Write( "Usage:  " );
  274. 			Console.ForegroundColor = ConsoleColor.White;
  275. 			Console.Error.WriteLine( "WGETLITE  url  [ /Response | /Save:filename ]  [ /Encoding:encoding ]" );
  276. 			Console.ResetColor( );
  277. 			Console.Error.WriteLine( );
  278. 			Console.Error.Write( "Where:  " );
  279. 			Console.ForegroundColor = ConsoleColor.White;
  280. 			Console.Error.Write( "/R" );
  281. 			Console.ResetColor( );
  282. 			Console.Error.WriteLine( "esponse returns server response code only" );
  283. 			Console.ForegroundColor = ConsoleColor.White;
  284. 			Console.Error.Write( "        /S" );
  285. 			Console.ResetColor( );
  286. 			Console.Error.WriteLine( "ave     saves downloaded content to specified file" );
  287. 			Console.ForegroundColor = ConsoleColor.White;
  288. 			Console.Error.Write( "        /E" );
  289. 			Console.ResetColor( );
  290. 			Console.Error.WriteLine( "ncoding specifies encoding of url; accepted values are:" );
  291. 			Console.ForegroundColor = ConsoleColor.White;
  292. 			Console.Error.Write( "                  A" );
  293. 			Console.ResetColor( );
  294. 			Console.Error.Write( "SCII, " );
  295. 			Console.ForegroundColor = ConsoleColor.White;
  296. 			Console.Error.Write( "U" );
  297. 			Console.ResetColor( );
  298. 			Console.Error.Write( "nicode, " );
  299. 			Console.ForegroundColor = ConsoleColor.White;
  300. 			Console.Error.Write( "U" );
  301. 			Console.ResetColor( );
  302. 			Console.Error.Write( "nicode (" );
  303. 			Console.ForegroundColor = ConsoleColor.White;
  304. 			Console.Error.Write( "BE" );
  305. 			Console.ResetColor( );
  306. 			Console.Error.Write( "), " );
  307. 			Console.ForegroundColor = ConsoleColor.White;
  308. 			Console.Error.Write( "U" );
  309. 			Console.ResetColor( );
  310. 			Console.Error.Write( "TF-" );
  311. 			Console.ForegroundColor = ConsoleColor.White;
  312. 			Console.Error.Write( "7" );
  313. 			Console.ResetColor( );
  314. 			Console.Error.Write( ", " );
  315. 			Console.ForegroundColor = ConsoleColor.White;
  316. 			Console.Error.Write( "U" );
  317. 			Console.ResetColor( );
  318. 			Console.Error.Write( "TF-" );
  319. 			Console.ForegroundColor = ConsoleColor.White;
  320. 			Console.Error.Write( "8" );
  321. 			Console.ResetColor( );
  322. 			Console.Error.Write( ", " );
  323. 			Console.ForegroundColor = ConsoleColor.White;
  324. 			Console.Error.Write( "U" );
  325. 			Console.ResetColor( );
  326. 			Console.Error.Write( "TF-" );
  327. 			Console.ForegroundColor = ConsoleColor.White;
  328. 			Console.Error.WriteLine( "32" );
  329. 			Console.ResetColor( );
  330. 			Console.Error.WriteLine( );
  331. 			Console.Error.WriteLine( "Notes:  On errors the actual HTTP response code is returned as 'errorlevel'." );
  332. 			Console.Error.WriteLine( "        Usually specifying the encoding won't be necessary." );
  333. 			Console.Error.Write( "        Switches may be abbreviated, e.g. " );
  334. 			Console.ForegroundColor = ConsoleColor.White;
  335. 			Console.Error.Write( "/E" );
  336. 			Console.ResetColor( );
  337. 			Console.Error.Write( ":" );
  338. 			Console.ForegroundColor = ConsoleColor.White;
  339. 			Console.Error.Write( "U8" );
  340. 			Console.ResetColor( );
  341. 			Console.Error.Write( " instead of " );
  342. 			Console.ForegroundColor = ConsoleColor.White;
  343. 			Console.Error.Write( "/E" );
  344. 			Console.ResetColor( );
  345. 			Console.Error.Write( "ncoding:" );
  346. 			Console.ForegroundColor = ConsoleColor.White;
  347. 			Console.Error.Write( "UTF-8" );
  348. 			Console.Error.WriteLine( "." );
  349. 			Console.ResetColor( );
  350. 			Console.Error.WriteLine( "        Based on a blog post by Sugree Phatanapherom:" );
  351. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  352. 			Console.Error.WriteLine( "        http://www.howforge.com/how-to-implement-simple-wget-in-c" );
  353. 			Console.ResetColor( );
  354. 			Console.Error.WriteLine( );
  355. 			Console.Error.WriteLine( "Written by Rob van der Woude" );
  356. 			Console.Error.WriteLine( "http://www.robvanderwoude.com" );
  357. 			return 1;
  358. 		}
  359.  
  360. 		#endregion Error Handling
  361. 	}
  362. }
  363.