Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for savefilebox.cs

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using System.Windows.Forms;
  7.  
  8.  
  9. namespace RobvanderWoude
  10. {
  11. 	class SaveFileBox
  12. 	{
  13. 		static string progver = "1.02";
  14.  
  15. 		[STAThread]
  16. 		static int Main( string[] args )
  17. 		{
  18. 			using ( SaveFileDialog dialog = new SaveFileDialog( ) )
  19. 			{
  20. 				string filter = "All files (*.*)|*.*";
  21. 				string ext = ".*";
  22. 				string folder = Directory.GetCurrentDirectory( );
  23. 				string title = "SaveFileBox,  Version " + progver;
  24. 				bool forceext = false;
  25. 				bool overwrite = false;
  26. 				bool verbose = false;
  27. 				bool forcespec = false;
  28. 				bool promptspec = false;
  29.  
  30. 				#region Command Line Parsing
  31.  
  32. 				foreach ( string arg in args )
  33. 				{
  34. 					if ( arg == "/?" )
  35. 					{
  36. 						return ShowHelp( );
  37. 					}
  38. 				}
  39. 				if ( args.Length > 5 )
  40. 				{
  41. 					return ShowHelp( "Too many command line arguments" );
  42. 				}
  43. 				if ( args.Length > 0 )
  44. 				{
  45. 					filter = args[0];
  46. 					ext = Regex.Match( filter, @"(\.[^.]+)$", RegexOptions.IgnoreCase ).Groups[0].ToString( );
  47. 					if ( String.IsNullOrWhiteSpace( ext ) )
  48. 					{
  49. 						return ShowHelp( "Invalid filetype specification" );
  50. 					}
  51. 					// If only "*.ext" is specified, use "ext files (*.ext)|*.ext" instead
  52. 					if ( Regex.IsMatch( filter, @"^\*\.(\*|\w+)$" ) )
  53. 					{
  54. 						if ( ext == ".*" )
  55. 						{
  56. 							filter = String.Format( "All files (*.{0})|*.{0}", ext );
  57. 						}
  58. 						else
  59. 						{
  60. 							filter = String.Format( "{0} files (*.{0})|*.{0}", ext );
  61. 						}
  62. 					}
  63. 					// Use "All files" filter if not specified
  64. 					if ( String.IsNullOrWhiteSpace( filter ) )
  65. 					{
  66. 						filter = "All files (*.*)|*.*";
  67. 					}
  68. 					// Optional second command line argument is start folder
  69. 					if ( args.Length > 1 )
  70. 					{
  71. 						try
  72. 						{
  73. 							folder = Path.GetFullPath( args[1] );
  74. 						}
  75. 						catch ( ArgumentException )
  76. 						{
  77. 							// Assuming the error was caused by a trailing bacslash in doublequotes
  78. 							folder = args[1].Substring( 0, args[1].IndexOf( '"' ) );
  79. 							folder = Path.GetFullPath( folder + "." );
  80. 						}
  81. 						if ( !Directory.Exists( folder ) )
  82. 						{
  83. 							return ShowHelp( "Invalid folder \"{0}\"", folder );
  84. 						}
  85. 						// Optional third command line argument is dialog title
  86. 						if ( args.Length > 2 )
  87. 						{
  88. 							title = args[2];
  89. 							if ( args.Length > 3 )
  90. 							{
  91. 								foreach ( string arg in args.Skip<string>( 2 ) )
  92. 								{
  93. 									switch ( arg.ToUpper( ) )
  94. 									{
  95. 										case "/F":
  96. 											if ( forcespec )
  97. 											{
  98. 												return ShowHelp( "Duplicate command line switch /F" );
  99. 											}
  100. 											forceext = true;
  101. 											forcespec = true;
  102. 											break;
  103. 										case "/Q":
  104. 											if ( promptspec )
  105. 											{
  106. 												return ShowHelp( "Duplicate command line switches or invalid combination" );
  107. 											}
  108. 											overwrite = true;
  109. 											promptspec = true;
  110. 											break;
  111. 										case "/V":
  112. 											if ( promptspec )
  113. 											{
  114. 												return ShowHelp( "Duplicate command line switches or invalid combination" );
  115. 											}
  116. 											verbose = true;
  117. 											promptspec = true;
  118. 											break;
  119. 										default:
  120. 											return ShowHelp( "Invalid command line argument \"{0}\"", arg );
  121. 									}
  122. 								}
  123. 							}
  124. 						}
  125. 					}
  126. 				}
  127.  
  128. 				#endregion Command Line Parsing
  129.  
  130.  
  131. 				dialog.Filter = filter;
  132. 				dialog.FilterIndex = 1;
  133. 				dialog.InitialDirectory = folder;
  134. 				dialog.AddExtension = forceext;
  135. 				dialog.DefaultExt = ext;
  136. 				dialog.CheckFileExists = false;
  137. 				dialog.CheckPathExists = !overwrite;
  138. 				dialog.CreatePrompt = false;
  139. 				dialog.OverwritePrompt = false;
  140. 				dialog.SupportMultiDottedExtensions = true;
  141. 				dialog.Title = title;
  142. 				dialog.RestoreDirectory = true;
  143. 				if ( dialog.ShowDialog( ) == DialogResult.OK )
  144. 				{
  145. 					string filename = dialog.FileName;
  146. 					if ( forceext )
  147. 					{
  148. 						string newext = Path.GetExtension( filename );
  149. 						if ( String.Compare( newext, ext, true ) != 0 )
  150. 						{
  151. 							filename += ext;
  152. 						}
  153. 					}
  154. 					if ( File.Exists( filename ) )
  155. 					{
  156. 						// File exists
  157. 						if ( !overwrite )
  158. 						{
  159. 							string prompt = String.Format( "The file \"{0}\" already exists.\n\nDo you want to replace it?", Path.GetFileName( filename ) );
  160. 							string caption = "Overwrite File?";
  161. 							MessageBoxButtons buttons = MessageBoxButtons.YesNo;
  162. 							MessageBoxIcon icon = MessageBoxIcon.Warning;
  163. 							DialogResult result = MessageBox.Show( prompt, caption, buttons, icon, MessageBoxDefaultButton.Button2 );
  164. 							if ( result != DialogResult.Yes )
  165. 							{
  166. 								// Canceled
  167. 								return 2;
  168. 							}
  169. 						}
  170. 						// Overwrite approved
  171. 						Console.WriteLine( filename );
  172. 						return 3;
  173. 					}
  174. 					else
  175. 					{
  176. 						// File does not exist
  177. 						if ( verbose )
  178. 						{
  179. 							string prompt = String.Format( "The file \"{0}\" does not exist.\n\nDo you want to create it?", Path.GetFileName( filename ) );
  180. 							string caption = "Create File?";
  181. 							MessageBoxButtons buttons = MessageBoxButtons.YesNo;
  182. 							MessageBoxIcon icon = MessageBoxIcon.Question;
  183. 							DialogResult result = MessageBox.Show( prompt, caption, buttons, icon, MessageBoxDefaultButton.Button1 );
  184. 							if ( result != DialogResult.Yes )
  185. 							{
  186. 								// Canceled
  187. 								return 2;
  188. 							}
  189. 						}
  190. 						// OK
  191. 						Console.WriteLine( filename );
  192. 						return 0;
  193. 					}
  194. 				}
  195. 				else
  196. 				{
  197. 					// Canceled
  198. 					return 2;
  199. 				}
  200. 			}
  201. 		}
  202.  
  203. 		static int ShowHelp( params string[] errmsg )
  204. 		{
  205. 			/*
  206. 			SaveFileBox.exe,  Version 1.02
  207. 			Batch tool to present a Save File dialog and return the selected file path
  208.  
  209. 			Usage:  SAVEFILEBOX  "filetypes"  "startfolder"  "title"  options
  210.  
  211. 			Where:  filetypes    file type(s) in format "description (*.ext)|*.ext"
  212. 			                     or just "*.ext" (default: "All files (*.*)|*.*")
  213. 			        startfolder  the initial folder the dialog will show on opening
  214. 			                     (default: current directory)
  215. 			        title        the caption in the dialog's title bar
  216. 			                     (default: program name and version)
  217. 			        options      /F    Force specified extension
  218. 			                     /Q    Quiet mode: do not check if the file exists
  219. 			                     /V    Verbose mode: prompt for confirmation
  220. 			                     (default: prompt only if file exists)
  221.  
  222. 			Notes:  This batch tool does not actually save the file, it is only intended
  223. 			        to interactively specify a file path, which can be used by the calling
  224. 			        batch file.
  225. 			        All command line arguments are optional, but each argument requires
  226. 			        the ones preceeding it, e.g. "startfolder" requires "filetypes" but
  227. 			        not necessarily "title" and options.
  228. 			        Options /Q and /V are mutually exclusive.
  229. 			        If the filetypes filter is in "*.ext" format, "ext files (*.ext)|*.ext"
  230. 			        will be used instead.
  231. 			        The full path of the selected file is written to Standard Output
  232. 			        if OK was clicked, or an empty string if Cancel was clicked.
  233. 			        The return code will be 0 on success, 1 in case of (command line)
  234. 			        errors, 2 on Cancel, 3 if not in Quiet mode and file exists.
  235.  
  236. 			Written by Rob van der Woude
  237. 			http://www.robvanderwoude.com
  238. 			*/
  239.  
  240. 			#region Error Message
  241.  
  242. 			if ( errmsg.Length > 0 )
  243. 			{
  244. 				List<string> errargs = new List<string>( errmsg );
  245. 				errargs.RemoveAt( 0 );
  246. 				Console.Error.WriteLine( );
  247. 				Console.ForegroundColor = ConsoleColor.Red;
  248. 				Console.Error.Write( "ERROR:\t" );
  249. 				Console.ForegroundColor = ConsoleColor.White;
  250. 				Console.Error.WriteLine( errmsg[0], errargs.ToArray( ) );
  251. 				Console.ResetColor( );
  252. 			}
  253.  
  254. 			#endregion Error Message
  255.  
  256. 			Console.Error.WriteLine( );
  257.  
  258. 			Console.Error.WriteLine( "SaveFileBox.exe,  Version {0}", progver );
  259.  
  260. 			Console.Error.WriteLine( "Batch tool to present a Save File dialog and return the selected file path" );
  261.  
  262. 			Console.Error.WriteLine( );
  263.  
  264. 			Console.Error.Write( "Usage:  " );
  265. 			Console.ForegroundColor = ConsoleColor.White;
  266. 			Console.Error.WriteLine( "SAVEFILEBOX  \"filetypes\"  \"startfolder\"  \"title\"  options" );
  267. 			Console.ResetColor( );
  268.  
  269. 			Console.Error.WriteLine( );
  270.  
  271. 			Console.Error.Write( "Where:  " );
  272. 			Console.ForegroundColor = ConsoleColor.White;
  273. 			Console.Error.Write( "filetypes" );
  274. 			Console.ResetColor( );
  275. 			Console.Error.Write( "    file type(s) in format " );
  276. 			Console.ForegroundColor = ConsoleColor.White;
  277. 			Console.Error.WriteLine( "\"description (*.ext)|*.ext\"" );
  278. 			Console.ResetColor( );
  279.  
  280. 			Console.Error.Write( "                     or just " );
  281. 			Console.ForegroundColor = ConsoleColor.White;
  282. 			Console.Error.Write( "\"*.ext\"" );
  283. 			Console.ResetColor( );
  284. 			Console.Error.Write( " (default: " );
  285. 			Console.ForegroundColor = ConsoleColor.White;
  286. 			Console.Error.Write( "\"All files (*.*)|*.*\"" );
  287. 			Console.ResetColor( );
  288. 			Console.Error.WriteLine( ")" );
  289.  
  290. 			Console.ForegroundColor = ConsoleColor.White;
  291. 			Console.Error.Write( "        startfolder" );
  292. 			Console.ResetColor( );
  293. 			Console.Error.WriteLine( "  the initial folder the dialog will show on opening" );
  294.  
  295. 			Console.Error.WriteLine( "                     (default: current directory)" );
  296.  
  297. 			Console.ForegroundColor = ConsoleColor.White;
  298. 			Console.Error.Write( "        title" );
  299. 			Console.ResetColor( );
  300. 			Console.Error.WriteLine( "        the caption in the dialog's title bar" );
  301.  
  302. 			Console.Error.WriteLine( "                     (default: \"SaveFileBox,  Version {0})\"", progver );
  303.  
  304. 			Console.ForegroundColor = ConsoleColor.White;
  305. 			Console.Error.Write( "        options      /F    F" );
  306. 			Console.ResetColor( );
  307. 			Console.Error.WriteLine( "orce specified extension" );
  308.  
  309. 			Console.ForegroundColor = ConsoleColor.White;
  310. 			Console.Error.Write( "                     /Q    Q" );
  311. 			Console.ResetColor( );
  312. 			Console.Error.WriteLine( "uiet mode: do not check if the file exists" );
  313.  
  314. 			Console.ForegroundColor = ConsoleColor.White;
  315. 			Console.Error.Write( "                     /V    V" );
  316. 			Console.ResetColor( );
  317. 			Console.Error.WriteLine( "erbose mode: prompt for confirmation" );
  318.  
  319. 			Console.Error.WriteLine( "                     (default: prompt only if file exists)" );
  320.  
  321. 			Console.Error.WriteLine( );
  322.  
  323. 			Console.Error.WriteLine( "Notes:  This batch tool does not actually save the file, it is only intended" );
  324.  
  325. 			Console.Error.WriteLine( "        to interactively specify a file path, which can be used by the calling" );
  326.  
  327. 			Console.Error.WriteLine( "        batch file." );
  328.  
  329. 			Console.Error.WriteLine( "        All command line arguments are optional, but each argument requires" );
  330.  
  331. 			Console.Error.Write( "        the ones preceeding it, e.g. " );
  332. 			Console.ForegroundColor = ConsoleColor.White;
  333. 			Console.Error.Write( "\"startfolder\"" );
  334. 			Console.ResetColor( );
  335. 			Console.Error.Write( " requires " );
  336. 			Console.ForegroundColor = ConsoleColor.White;
  337. 			Console.Error.Write( "\"filetypes\"" );
  338. 			Console.ResetColor( );
  339. 			Console.Error.WriteLine( " but" );
  340.  
  341. 			Console.Error.Write( "        not necessarily " );
  342. 			Console.ForegroundColor = ConsoleColor.White;
  343. 			Console.Error.Write( "\"title\"" );
  344. 			Console.ResetColor( );
  345. 			Console.Error.Write( " and " );
  346. 			Console.ForegroundColor = ConsoleColor.White;
  347. 			Console.Error.Write( "options" );
  348. 			Console.ResetColor( );
  349. 			Console.Error.WriteLine( "." );
  350.  
  351. 			Console.Error.Write( "        Options " );
  352. 			Console.ForegroundColor = ConsoleColor.White;
  353. 			Console.Error.Write( "/Q" );
  354. 			Console.ResetColor( );
  355. 			Console.Error.Write( " and " );
  356. 			Console.ForegroundColor = ConsoleColor.White;
  357. 			Console.Error.Write( "/V" );
  358. 			Console.ResetColor( );
  359. 			Console.Error.WriteLine( " are mutually exclusive." );
  360.  
  361. 			Console.Error.Write( "        If the filetypes filter is in " );
  362. 			Console.ForegroundColor = ConsoleColor.White;
  363. 			Console.Error.Write( "\"*.ext\"" );
  364. 			Console.ResetColor( );
  365. 			Console.Error.Write( " format, " );
  366. 			Console.ForegroundColor = ConsoleColor.White;
  367. 			Console.Error.WriteLine( "\"ext files (*.ext)|*.ext\"" );
  368. 			Console.ResetColor( );
  369. 			Console.Error.WriteLine( "        will be used instead." );
  370.  
  371. 			Console.Error.WriteLine( "        The full path of the selected file is written to Standard Output" );
  372.  
  373. 			Console.Error.WriteLine( "        if OK was clicked, or an empty string if Cancel was clicked." );
  374.  
  375. 			Console.Error.WriteLine( "        The return code will be 0 on success, 1 in case of (command line)" );
  376.  
  377. 			Console.Error.WriteLine( "        errors, 2 on Cancel, 3 if not in Quiet mode and file exists." );
  378.  
  379. 			Console.Error.WriteLine( );
  380.  
  381. 			Console.Error.WriteLine( "Written by Rob van der Woude" );
  382.  
  383. 			Console.Error.WriteLine( "http://www.robvanderwoude.com" );
  384.  
  385. 			return 1;
  386. 		}
  387. 	}
  388. }
  389.  

page last uploaded: 2018-12-04, 10:47