Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for word2openoffice.cs

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using Word = Microsoft.Office.Interop.Word;
  5.  
  6.  
  7. namespace Word2OpenOffice
  8. {
  9. 	class Word2OpenOffice
  10. 	{
  11. 		static string progver = "1.00";
  12.  
  13.  
  14. 		static bool debug = false;
  15.  
  16.  
  17. 		static int Main(string[] args)
  18. 		{
  19. 			#region Initialize Variables
  20.  
  21. #if DEBUG
  22. 			debug = true;
  23. #endif
  24. 			bool overwrite = false;
  25. 			bool prompt = false;
  26. 			int converted = 0;
  27. 			int failed = 0;
  28. 			int matchingfiles = 0;
  29. 			int overwritten = 0;
  30. 			int skipped = 0;
  31. 			string inputfilespec = null;
  32. 			string inputfileext;
  33. 			string parentfolder;
  34.  
  35. 			#endregion Initialize Variables
  36.  
  37.  
  38. 			#region Command Line Parsing
  39.  
  40. 			if ( args.Length == 0 || args.Length > 2 )
  41. 			{
  42. 				return ShowHelp( );
  43. 			}
  44. 			foreach ( string arg in args )
  45. 			{
  46. 				switch ( arg.ToUpper( ) )
  47. 				{
  48. 					case "/?":
  49. 						return ShowHelp( );
  50. 					case "/O":
  51. 						if ( overwrite )
  52. 						{
  53. 							return ShowHelp( "Duplicate command line switch /O" );
  54. 						}
  55. 						overwrite = true;
  56. 						break;
  57. 					case "/P":
  58. 						if ( prompt )
  59. 						{
  60. 							return ShowHelp( "Duplicate command line switch /P" );
  61. 						}
  62. 						prompt = true;
  63. 						break;
  64. 					default:
  65. 						if ( string.IsNullOrWhiteSpace( inputfilespec ) && arg.IndexOfAny( "/?;,<>".ToCharArray( ) ) == -1 )
  66. 						{
  67. 							inputfilespec = arg;
  68. 						}
  69. 						else
  70. 						{
  71. 							return ShowHelp( "Invalid command line argument \"{0}\"", arg );
  72. 						}
  73. 						break;
  74. 				}
  75. 			}
  76.  
  77. 			#endregion Command Line Parsing
  78.  
  79.  
  80. 			#region Command Line Validation
  81.  
  82. 			// Validate input filespec
  83. 			if ( string.IsNullOrWhiteSpace( inputfilespec ) )
  84. 			{
  85. 				return ShowHelp( "Please specify an input file" );
  86. 			}
  87. 			parentfolder = Directory.GetParent( inputfilespec ).FullName;
  88. 			if ( !Directory.Exists( parentfolder ) )
  89. 			{
  90. 				return ShowHelp( "Directory \"{0}\" not found", parentfolder );
  91. 			}
  92. 			inputfileext = Path.GetExtension( inputfilespec ).ToLower( );
  93. 			if ( !inputfileext.Contains( "*" ) && inputfileext != ".doc" && inputfileext != ".docx" )
  94. 			{
  95. 				return ShowHelp( "Invalid file format for \"{0}\"", inputfilespec );
  96. 			}
  97.  
  98. 			// check mutually exclusive switches /O and /P
  99. 			if ( overwrite && prompt )
  100. 			{
  101. 				Console.ForegroundColor = ConsoleColor.Red;
  102. 				Console.Error.Write( "WARNING:\t" );
  103. 				Console.ForegroundColor = ConsoleColor.White;
  104. 				Console.Error.WriteLine( "/O and /P switches are mutually exclusive; ignoring /O" );
  105. 				Console.ResetColor( );
  106. 				overwrite = false;
  107. 			}
  108.  
  109. 			#endregion Command Line Validation
  110.  
  111.  
  112. 			#region Iterate File List and Convert Each File
  113.  
  114. 			foreach ( string inputfile in Directory.GetFiles( parentfolder, Path.GetFileName( inputfilespec ) ) )
  115. 			{
  116. 				matchingfiles += 1;
  117. 				if ( debug )
  118. 				{
  119. 					Console.WriteLine( "[{0}]\t\"{1}\"", matchingfiles, inputfile );
  120. 				}
  121. 				if ( Path.GetExtension( inputfile ) != ".doc" && Path.GetExtension( inputfile ) != ".docx" )
  122. 				{
  123. 					Console.ForegroundColor = ConsoleColor.Yellow;
  124. 					Console.Write( "Skipped " );
  125. 					Console.ResetColor( );
  126. 					Console.WriteLine( "\"{0}\" because its extension is neither .DOC nor .DOCX", inputfile );
  127. 					skipped += 1;
  128. 					continue;
  129. 				}
  130. 				else
  131. 				{
  132. 					string outputfile = Path.ChangeExtension( inputfile, ".odt" );
  133. 					if ( File.Exists( outputfile ) )
  134. 					{
  135. 						if ( overwrite )
  136. 						{
  137. 							Console.ForegroundColor = ConsoleColor.Yellow;
  138. 							Console.Write( "Overwriting " );
  139. 							Console.ResetColor( );
  140. 							Console.WriteLine( "\"{0}\"", outputfile );
  141. 							overwritten += 1;
  142. 						}
  143. 						else if ( prompt )
  144. 						{
  145. 							Console.ForegroundColor = ConsoleColor.White;
  146. 							Console.Write( "Output file \"{0}\" already exists, do you want to overwrite it? [y/N] ", outputfile );
  147. 							Console.ResetColor( );
  148. 							string answer = Console.ReadKey( false ).Key.ToString( );
  149. 							if ( answer != "Y" )
  150. 							{
  151. 								Console.ForegroundColor = ConsoleColor.Yellow;
  152. 								Console.Write( "\nSkipping " );
  153. 								Console.ResetColor( );
  154. 								Console.WriteLine( "\"{0}\" at user's request", Path.GetFileName( inputfile ) );
  155. 								skipped += 1;
  156. 								continue;
  157. 							}
  158. 							else
  159. 							{
  160. 								Console.ForegroundColor = ConsoleColor.Yellow;
  161. 								Console.Write( "\nOverwriting " );
  162. 								Console.ResetColor( );
  163. 								Console.WriteLine( "\"{0}\" at user's request", Path.GetFileName( outputfile ) );
  164. 								overwritten += 1;
  165. 							}
  166. 						}
  167. 						else
  168. 						{
  169. 							Console.ForegroundColor = ConsoleColor.Yellow;
  170. 							Console.Write( "Skipped " );
  171. 							Console.ResetColor( );
  172. 							Console.WriteLine( "\"{0}\" because \"{1}\" already exists", Path.GetFileName( inputfile ), Path.GetFileName( outputfile ) );
  173. 							skipped += 1;
  174. 							continue;
  175. 						}
  176. 					}
  177. 					Console.Write( "Converting \"{0}\" . . . ", Path.GetFileName( inputfile ) );
  178. 					if ( WordConvert( inputfile, outputfile ) )
  179. 					{
  180. 						Console.ForegroundColor = ConsoleColor.Green;
  181. 						Console.WriteLine( "Success" );
  182. 						Console.ResetColor( );
  183. 						converted += 1;
  184. 					}
  185. 					else
  186. 					{
  187. 						Console.ForegroundColor = ConsoleColor.Red;
  188. 						Console.WriteLine( "Failed" );
  189. 						Console.ResetColor( );
  190. 						failed += 1;
  191. 					}
  192. 				}
  193. 			}
  194.  
  195. 			#endregion Iterate File List and Convert Each File
  196.  
  197.  
  198. 			// Show statistics
  199. 			Console.ForegroundColor = ConsoleColor.White;
  200. 			Console.Write( "\n{0} matching file names, ", matchingfiles );
  201. 			Console.ForegroundColor = ConsoleColor.Yellow;
  202. 			Console.Write( "{0} skipped, ", skipped );
  203. 			Console.ForegroundColor = ConsoleColor.Green;
  204. 			Console.Write( "{0} converted, ", converted );
  205. 			Console.ForegroundColor = ConsoleColor.Red;
  206. 			Console.Write( "{0} failed, ", failed );
  207. 			Console.ForegroundColor = ConsoleColor.Yellow;
  208. 			Console.WriteLine( "{0} overwritten", overwritten );
  209. 			Console.ResetColor( );
  210.  
  211. 			return 0;
  212. 		}
  213.  
  214.  
  215. 		static bool WordConvert( string inputpath, string outputpath )
  216. 		{
  217. 			try
  218. 			{
  219. 				Word.Application wordapp = new Word.Application( );
  220. 				wordapp.Visible = false;
  221. 				Word.Document worddoc = wordapp.Documents.Open( inputpath );
  222. 				// Save the entire original document with the new file name and file type
  223. 				worddoc.SaveAs( outputpath, Word.WdSaveFormat.wdFormatOpenDocumentText );
  224. 				// Close the document(s) and application
  225. 				object savechanges = Word.WdSaveOptions.wdDoNotSaveChanges;
  226. 				worddoc.Close( ref savechanges );
  227. 				wordapp.Quit( ref savechanges );
  228. 				return true;
  229. 			}
  230. 			catch ( Exception )
  231. 			{
  232. 				return false;
  233. 			}
  234. 		}
  235.  
  236.  
  237. 		static int ShowHelp( params string[] errmsg )
  238. 		{
  239. 			#region Help Text
  240.  
  241. 			/*
  242. 			Word2OpenOffice,  Version 1.00
  243. 			Open a Microsoft Word document and save it in OpenOffice ODT format
  244.  
  245. 			Usage:     Word2OpenOffice.exe  "wordfile"  [ Options ]
  246.  
  247. 			Where:     wordfile    Word document(s) to be converted (extension ".doc"
  248. 			                       or ".docx"; wildcard "*" allowed, e.g. "name*.doc*")
  249. 			Options:   /O          silently Overwrite existing output file(s)
  250. 			                       (default: abort or skip if output file exists)
  251. 			           /P          Prompt to overwrite existing output file(s)
  252. 			                       (default: abort or skip if output file exists)
  253.  
  254. 			Notes: [1] This program requires a "regular" (MSI based) Microsoft Word
  255. 			           (2007 or later) installation, it will fail on an MS Office
  256. 			           "click-to-run" installation.
  257. 			       [2] The converted output file(s) will have the same name and location
  258. 			           as the input file(s), with extension ".odt".
  259. 			       [3] If wildcards are used in the Word file names, and /O or /P switch
  260. 			           are not used, the program will display an error message in case an
  261. 			           output file already exists, but it will then continue to convert
  262. 			           the next file instead of aborting.
  263. 			       [4] If Word was already active when this program is started, any other
  264. 			           opened document(s) will be left alone, and only the document(s)
  265. 			           opened by this program will be closed.
  266.  
  267. 			Examples:  Word2OpenOffice.exe "D:\folder\myfile.doc"
  268. 			           will convert the file and save it to "D:\folder\myfile.odt"
  269.  
  270. 			           Word2OpenOffice.exe "D:\folder\*.doc*"
  271. 			           will convert all matching files and save them to "D:\folder\*.odt"
  272.  
  273. 			Written by Rob van der Woude
  274. 			http://www.robvanderwoude.com
  275. 			*/
  276.  
  277. 			#endregion Help Text
  278.  
  279.  
  280. 			#region Error Message
  281.  
  282. 			if ( errmsg.Length > 0 )
  283. 			{
  284. 				List<string> errargs = new List<string>( errmsg );
  285. 				errargs.RemoveAt( 0 );
  286. 				Console.Error.WriteLine( );
  287. 				Console.ForegroundColor = ConsoleColor.Red;
  288. 				Console.Error.Write( "ERROR:\t" );
  289. 				Console.ForegroundColor = ConsoleColor.White;
  290. 				Console.Error.WriteLine( errmsg[0], errargs.ToArray( ) );
  291. 				Console.ResetColor( );
  292. 			}
  293.  
  294. 			#endregion Error Message
  295.  
  296.  
  297. 			#region Display Help Text
  298.  
  299. 			Console.Error.WriteLine( );
  300.  
  301. 			Console.Error.WriteLine( "Word2OpenOffice,  Version {0}", progver );
  302.  
  303. 			Console.Error.WriteLine( "Open a Microsoft Word document and save it in OpenOffice ODT format" );
  304.  
  305. 			Console.Error.WriteLine( );
  306.  
  307. 			Console.Error.Write( "Usage:     " );
  308. 			Console.ForegroundColor = ConsoleColor.White;
  309. 			Console.Error.WriteLine( "Word2OpenOffice.exe  \"wordfile\"  [ Options ]" );
  310. 			Console.ResetColor( );
  311.  
  312. 			Console.Error.WriteLine( );
  313.  
  314. 			Console.Error.Write( "Where:     " );
  315. 			Console.ForegroundColor = ConsoleColor.White;
  316. 			Console.Error.Write( "wordfile" );
  317. 			Console.ResetColor( );
  318. 			Console.Error.WriteLine( "    Word document(s) to be converted (extension \".doc\"" );
  319.  
  320. 			Console.Error.WriteLine( "                       or \".docx\"; wildcard \"*\" allowed, e.g. \"name*.doc*\")" );
  321.  
  322. 			Console.Error.WriteLine( );
  323.  
  324. 			Console.Error.Write( "Options:   " );
  325. 			Console.ForegroundColor = ConsoleColor.White;
  326. 			Console.Error.Write( "/O" );
  327. 			Console.ResetColor( );
  328. 			Console.Error.Write( "          silently " );
  329. 			Console.ForegroundColor = ConsoleColor.White;
  330. 			Console.Error.Write( "O" );
  331. 			Console.ResetColor( );
  332. 			Console.Error.WriteLine( "verwrite existing output file(s)" );
  333.  
  334. 			Console.Error.WriteLine( "                       (default: abort or skip if output file exists)" );
  335.  
  336. 			Console.ForegroundColor = ConsoleColor.White;
  337. 			Console.Error.Write( "           /P          P" );
  338. 			Console.ResetColor( );
  339. 			Console.Error.WriteLine( "rompt to overwrite existing output file(s)" );
  340.  
  341. 			Console.Error.WriteLine( "                       (default: abort or skip if output file exists)" );
  342.  
  343. 			Console.Error.WriteLine( );
  344.  
  345. 			Console.Error.WriteLine( "Notes: [1] This program requires a \"regular\" (MSI based) Microsoft Word" );
  346.  
  347. 			Console.Error.WriteLine( "           (2007 or later) installation, it will fail on an MS Office" );
  348.  
  349. 			Console.Error.WriteLine( "           \"click-to-run\" installation" );
  350.  
  351. 			Console.Error.WriteLine( "       [2] The converted output file(s) will have the same name and location" );
  352.  
  353. 			Console.Error.WriteLine( "           as the input file(s), with extension \".odt\"." );
  354.  
  355. 			Console.Error.Write( "       [3] If wildcards are used in the Word file names, and " );
  356. 			Console.ForegroundColor = ConsoleColor.White;
  357. 			Console.Error.Write( "/O" );
  358. 			Console.ResetColor( );
  359. 			Console.Error.Write( " or " );
  360. 			Console.ForegroundColor = ConsoleColor.White;
  361. 			Console.Error.Write( "/P" );
  362. 			Console.ResetColor( );
  363. 			Console.Error.WriteLine( " switch" );
  364.  
  365. 			Console.Error.WriteLine( "           are not used, the program will display an error message in case an" );
  366.  
  367. 			Console.Error.WriteLine( "           output file already exists, but it will then continue to convert" );
  368.  
  369. 			Console.Error.WriteLine( "           the next file instead of aborting." );
  370.  
  371. 			Console.Error.WriteLine( "       [4] If Word was already active when this program is started, any other" );
  372.  
  373. 			Console.Error.WriteLine( "           opened document(s) will be left alone, and only the document(s)" );
  374.  
  375. 			Console.Error.WriteLine( "           opened by this program will be closed." );
  376.  
  377. 			Console.Error.WriteLine( );
  378.  
  379. 			Console.Error.Write( "Examples:  " );
  380. 			Console.ForegroundColor = ConsoleColor.White;
  381. 			Console.Error.WriteLine( "Word2OpenOffice.exe \"D:\\folder\\myfile.doc\"" );
  382. 			Console.ResetColor( );
  383.  
  384. 			Console.Error.WriteLine( "           will convert the file and save it to \"D:\\folder\\myfile.odt\"" );
  385.  
  386. 			Console.Error.WriteLine( );
  387.  
  388. 			Console.ForegroundColor = ConsoleColor.White;
  389. 			Console.Error.WriteLine( "           Word2OpenOffice.exe \"D:\\folder\\*.doc*\"" );
  390. 			Console.ResetColor( );
  391.  
  392. 			Console.Error.WriteLine( "           will convert all matching files and save them to \"D:\\folder\\*.odt\"" );
  393.  
  394. 			Console.Error.WriteLine( );
  395.  
  396. 			Console.Error.WriteLine( "Written by Rob van der Woude" );
  397.  
  398. 			Console.Error.WriteLine( "https://www.robvanderwoude.com" );
  399.  
  400. 			#endregion Display Help Text
  401.  
  402.  
  403. 			return 1;
  404. 		}
  405. 	}
  406. }
  407.  

page last modified: 2024-04-16; loaded in 0.0253 seconds