[ Home | Syllabus | Course Notes | Assignments | Search]
Function: print a file to the screen
Key Features: console program argument
passing, streamReader, exceptions
------
using System; using System.IO; // beyond simple console I/O class MyApp { static void Main (string[] args)// zero or more command line arguments { // Make sure a file name was entered on the command line if (args.Length == 0) { // arrays know their length Console.WriteLine ("Error: Missing file name"); return; } // Open the file and display its contents StreamReader reader = null; try { reader = new StreamReader (args[0]); for (string line = reader.ReadLine (); line != null; line = reader.ReadLine ()) Console.WriteLine (line); } catch (IOException e) { Console.WriteLine (e.Message); } finally { if (reader != null) reader.Close (); } } }
F1: comments in read are added for annotations (in addition to these footnotes)
F2: StreamReader is an important class that abstracts a file as a text stream of bytes - NOTE set to NULL
F3: Opens the file named as the first argument as a text stream for reading
F4: Common C# programming pattern
F5: Wraps block of code for exception handling
F6: Exceptions of type IOException are handled here
F7: prints readable error message set by code that detected the error
F8: A "finally" block executes both in normal and exception cases
Experiments: what can you easily learn from this program?
What triggers the exception
What if try/catch block removed
What are other operations on StreamReader objects
How to print a list of files passed in on the command line
others??
Collections are ubiquitous in programming - these
are "safe" from unauthorized accesses.
Can store any object derived from "System.Object"
ArrayList: Resizeable
BitArray
HashTable: Key/Value pairs
Queue/Stack
SortedList: sorted Key/Value pairs
Dynamic Arrays - some examples
ArrayList list = new ArrayList (); list.Add ("John"); list.Add ("Paul"); list.Add ("George"); list.Add ("Ringo");
ArrayList list = new ArrayList (); for (int i=0; i<100000; i++) list.Add (i);
// a much faster version ArrayList list = new ArrayList (100000); for (int i=0; i<100000; i++) list.Add (i);
// access
int i = (int) list[0]; // need to cast System.Object
// Iteration over an ArrayList
for (int i=0; i<list.Count; i++) Console.WriteLine (list[i]);
// You can also iterate with foreach:
foreach (int i in list) Console.WriteLine (i);
Can also remove items- with shifting of position
Can set array's (initial) capacity
Generalizes array to use arbitrary "key" as index
Hashtable table = new Hashtable (); table.Add ("Sunday", "Dimanche"); table.Add ("Monday", "Lundi"); table.Add ("Tuesday", "Mardi"); table.Add ("Wednesday", "Mercredi"); table.Add ("Thursday", "Jeudi"); table.Add ("Friday", "Vendredi"); table.Add ("Saturday", "Samedi");
// access is by "key"
string word = (string) table["Tuesday"];
// access is through underlying DictionaryEntry object
foreach (DictionaryEntry entry in table) Console.WriteLine ("Key={0}, Value={1}\n", entry.Key, entry.Value
Valuable tools for "parsing"
strings
I use regular expressions every couple of weeks
Regular expressions = finite state machines (CS390)
Regex regex = new Regex (@"\\"); string[] parts = regex.Split (@"c:\inetpub\wwwroot\wintellect"); foreach (string part in parts) Console.WriteLine (part);
And here’s the output:
c: inetpub wwwroot wintellect
Regex regex = new Regex ("<[^>]*>"); string[] parts = regex.Split ("<b>Every</b>good<h3>boy</h3>does<b>fine</b>"); foreach (string part in parts) Console.WriteLine (part);
And here’s the output:
Every good boy does fine
// one common use of regular expression is for validation
bool IsValid (string input) { Regex regex = new Regex ("^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}$"); return regex.IsMatch (input); }
Regex regex = new Regex ("href\\s*=\\s*\"[^\"]*\"", RegexOptions.IgnoreCase); StreamReader reader = new StreamReader ("Index.html"); for (string line = reader.ReadLine (); line != null; line = reader.ReadLine ()) { MatchCollection matches = regex.Matches (line); foreach (Match match in matches) Console.WriteLine (match.Value); }
//// to extract a substring - enclose that portion of the regular expression in "( )" //// and use Groups to get the substring (there may be more than one)
Regex regex = new Regex ("href\\s*=\\s*\"([^\"]*)\"", RegexOptions.IgnoreCase); StreamReader reader = new StreamReader ("Index.html"); for (string line = reader.ReadLine (); line != null; line = reader.ReadLine ()) { MatchCollection matches = regex.Matches (line); foreach (Match match in matches) Console.WriteLine (match.Groups[1]); }
WebRequest request = WebRequest.Create ("http://www.wintellect.com"); WebResponse response = request.GetResponse ();
GetResponse returns an HttpWebResponse object encapsulating the response. Calling GetResponseStream on HttpWebResponse returns a Stream object that you can wrap a reader around to read the response. The following code echoes the text of the response to a console window:
StreamReader reader = new StreamReader (response.GetResponseStream ()); for (string line = reader.ReadLine (); line != null; line = reader.ReadLine ()) Console.WriteLine (line) reader.Close ();
Function: lists all hyperlinks in a web page
Objective: Demonstrate web access and regular expressions
using System; using System.IO; using System.Net; using System.Text.RegularExpressions; class MyApp { static void Main (string[] args) { if (args.Length == 0) { Console.WriteLine ("Error: Missing URL"); // common in command line console programs return; } StreamReader reader = null; try { WebRequest request = WebRequest.Create (args[0]); WebResponse response = request.GetResponse (); reader = new StreamReader (response.GetResponseStream ()); string content = reader.ReadToEnd (); Regex regex = new Regex ("href\\s*=\\s*\"([^\"]*)\"", RegexOptions.IgnoreCase); MatchCollection matches = regex.Matches (content); foreach (Match match in matches) Console.WriteLine (match.Groups[1]); } catch (Exception e) { Console.WriteLine (e.Message); } finally { if (reader != null) reader.Close (); } } }
F10: Opens a web page URL
F11: and gets the response web page
F12: expression says match "href" followed by some white space followed by an equals sing "=" followed by white space followed by a quote (") THEN remember the match you make of all characters (denoted by the asterisc (*)) up to another quote (that is what the parenthesis are doing) followed by the ending quote
F13: enumerate all matches
F14: get the text that matched inside the parentheses