public static int Main(String[] args) { try { // Parse the command-line arguments WordCountArgParser ap = new WordCountArgParser(); if (!ap.Parse(args)) { // An error occurrend while parsing return 1; } // If an output file was specified on the command-line, use it FileStream fsOut = null; StreamWriter sw = null; if (ap.OutputFile != null) { fsOut = new FileStream(ap.OutputFile, FileMode.Create, FileAccess.Write, FileShare.None); sw = new StreamWriter(fsOut, ap.FileEncoding); // By associating the StreamWriter with the console, the rest of // the code can think it's writing to the console but the console // object redirects the output to the StreamWriter Console.SetOut(sw); } // Create a WordCounter object to keep running statistics WordCounter wc = new WordCounter(); // Write the table header Console.WriteLine("Lines\tWords\tChars\tBytes\tPathname"); // Iterate over the user-specified files IEnumerator e = ap.GetPathnameEnumerator(); while (e.MoveNext()) { Int64 NumLines, NumWords, NumChars, NumBytes; // Calculate the words stats for this file wc.CountStats((String)e.Current, ap.FileEncoding, out NumLines, out NumWords, out NumChars, out NumBytes); // Display the results String[] StrArgs = new String[] { NumLines.ToString(), NumWords.ToString(), NumChars.ToString(), NumBytes.ToString(), (String) e.Current }; Console.WriteLine(String.Format("{0,5}\t{1,5}\t{2,5}\t{3,5}\t{4,5}", StrArgs)); } // Done processing all files, show the totals Console.WriteLine("-----\t-----\t-----\t-----\t---------------------"); Console.WriteLine(String.Format("{0,5}\t{1,5}\t{2,5}\t{3,5}\tTotal in all files", new object[] { wc.TotalLines, wc.TotalWords, wc.TotalChars, wc.TotalBytes } )); // If the user wants to see the word usage alphabetically, show it if (ap.ShowAlphabeticalWordUsage) { IDictionaryEnumerator de = wc.GetWordsAlphabeticallyEnumerator(); Console.WriteLine(String.Format("Word usage sorted alphabetically ({0} unique words)", wc.UniqueWords)); while (de.MoveNext()) { Console.WriteLine(String.Format("{0,5}: {1}", de.Value, de.Key)); } } // If the user wants to see the word usage by occurrence, show it if (ap.ShowOccurrenceWordUsage) { IDictionaryEnumerator de = wc.GetWordsByOccurrenceEnumerator(); Console.WriteLine(String.Format("Word usage sorted by occurrence ({0} unique words)", wc.UniqueWords)); while (de.MoveNext()) { Console.WriteLine(String.Format("{0,5}: {1}", ((WordCounter.WordOccurrence)de.Key).Occurrences, ((WordCounter.WordOccurrence)de.Key).Word)); } } // Explicitly close the console to guarantee that the StreamWriter object (sw) is flushed Console.Out.Close(); if (fsOut != null) fsOut.Close(); } catch(Exception e) { Console.WriteLine("Exception: " + e.Message); } return 0; }