windows programming using c# regular expressions, files & directories delegates
TRANSCRIPT
3
Regular Expressions
A regular expression is some text which is designed to match other text
You have seen one form of this as the wildcards used to match filenames Eg. *.exe
The regular expressions used by .NET are based on Perl5 regular expressions
These are different from the ones used to match file names on the command line
4
Regular Expressions
The simplest form of regular expression is one which matches itself“hello”This will match the text “hello”
In addition to regular characters, regex supports various metacharacters
These all have special meanings and instruct the regex to match different strings
5
Any Character
The simplest metacharacter is the “.” which will match any single character
“a.b” will match “aab” “abb” “acb” “axb” Or any other 3 character string beginning with a and
ending with b
6
Escape Characters
But what if you want to search for a string with a period in it?
Then you must escape the special meaning of the period as a metacharacter and restore it to a plain old period
Backslash is the escape character“a\.b” matches the single string “a.b”
7
Multiple Occurrences
There are metacharacters to represent multiple occurrences of the character in front of them
“a*” Any number of a’s
“ab?c” “ac” or “abc”
“ab+c” “abc” or “abbc” or …
“a.+b” “a” followed by 1 or more
chars and a “b”
Char Meaning
? Zero or once
* Zero or more
+ Once or more
8
Specific Occurrences
You can also specify a specific number of times a character can occur
It has several forms {3} – exactly 3 occurrences {3,} – 3 or more occurrences {3, 8} – between 3 and 8 occurrences
“.{3,4}ane” will match “hexane” “pentane” “butane” “propane”
9
Alternatives
Often, you want to match one of several strings
This can be done by grouping the options in parentheses and using the |
“(iso|cyclo)pentane” matches“isopentane”“cyclopentane”
10
Closures
At times, you need to match one of a set of characters This can be done by placing the characters in square
brackets “[cbf]at” matches
“cat”, “bat” and “fat”
Runs of character can use a dash “[a-z0-9-]”
Matches any lower case letter or digit or dash
The use of a caret reverses the meaning “[^a-z]”
Matches any character other than a lower-case letter
11
String Ends
“^” matches the beginning of the string “$” matches the end of string “abc$”
Matches “abc” only at the end of the string “^abc”
Matches “abc” only at the beginning of the string
12
Special Metacharacters
Symbol Meaning
\w Any word character (alphanumeric or _)
\W Any non-word character
\s Any whitespace character (space, tab, newline)
\S Any non-whitespace character
\d Any digit
\D Any non-digit
\b Any word boundary character
\B Any character not a word boundary
13
Regular Expressions in C#
C# provides System.Text.RegularExpressions.Regex
Represents a regular expression Match() -- finds first match Matches() -- finds all matches Split() – Splits into an array of strings Replace – replaces matched text
Match Represents the result of a single regex match
MatchCollection Represents the results of multiple matches
Group Represents the match of multiple expressions
14
Matching Strings
To match a regular expression Regex.Match(string input)
This returns a Match instance with Value – the matched substring Index – where the match occurred Length – the length of the match Success – true if anything was matched
To find the next match Match.MatchNext()
* see RegexDemo
15
Matching Strings
string input = "propane butane hexane septane heptane decane";
string expr ="h.{2,3}ane";Regex rx = new Regex(expr);Match m = rx.Match(input);while(m.Success) { Console.WriteLine("found \"{0}\" of length {1} at
position {2}", m.Value, m.Length, m.Index);
m = m.NextMatch();}
16
Splitting Strings
The Split method splits a string into an array of strings where the matches are found
The matched characters are discardedstring[] Split(string input)
17
Splitting Strings
string input = "A cat, a hat and a mouse";string sepRegex = " |, ";Regex rx = new Regex(sepRegex);string[] words = rx.Split(input);Console.WriteLine("Split Demo\ninput={0}", input);
foreach (string s in words) { Console.WriteLine(s);}
18
Replacing Text
The Replace method is used to replace all matching text with replacement text string Regex.Replace(string input)
string input = "I was\twalking while”; Regex rx = new Regex(@"\s+");string result = rx.Replace(input, " ");Console.WriteLine("Replace Demo\ninput={0}\
nresult={1}", input, result);
20
Exceptions
Exceptions are handled in much the same way as in Java
C# has a try-catch-finally statementtrystatement
catchstatement
[finallystatement]
21
Exceptions
This differs from Java in that you can have a catch without a parameter which will catch every exception
Unfortunately, there is no exception to get information from when it is done this way
try {// some statements
}catch { // no parameters, so catch all
Console.WriteLine(“unknown exception caught”);}
22
The Exception Class
System.Exception is the root of all exception classes
The constructors areException()
Exception(string msg)
Exception(string msg, Exception cause)
23
The Exception Class
The final form of the constructor is used to envelop an exception in another exception
This is useful when a system exception is thrown and you want to wrap it in a more meaningful application exception
Numerous properties provide access to the contents of the Exception
24
Exception Properties
Property Explanation
Data A read-only property implementing IDictionary. Might contain key/value pairs relating to the exception or might be null.
HelpLink A string containing a URL or other reference. Is read/write.
InnerException A nested exception which can be set only by the constructor.
Message A string message explaining the exception.
Source A string which can be get/set to identify the source of the exception.
StackTrace A string showing the call path when the exception was thrown.
25
ApplicationException Class
Direct subclasses of Exception are thrown only by the system
Applications should throw exceptions derived from ApplicationException
ApplicationException extends Exception but adds no new members
26
Throwing Exceptions
To throw an exceptionthrow new ApplicationException(“broken”);
Both Java and C++ allow methods which throw exceptions to declare them
C# does not provide a way for a method to declare that an exception is thrown
You must consult the documentation to determine if an exception is thrown by a method
27
Custom Exceptions
You can create custom exceptions by extending ApplicationExceptionProvide constructors which call the base class
constructorsAdd any fields and constructor parameters for
your specific exception informationAdd properties/methods for the new fields
29
Files & Directories
This section will explore how to work with files and directories
We begin with directories Directory
Contains static methods for creating, deleting, moving and listing directories
DirectoryInfo An instance represents a directory Has instance methods for manipulating the directory
30
Directory Class
Method Description
CreateDirectory( ) Creates all directories and subdirectories specified by its path parameter.
GetCreationTime() Returns and sets the time the specified directory was created.
GetDirectories() Gets named directories.
GetLogicalDrives() Returns the names of all the logical drives in the form
<drive>:\.
GetFiles() Returns the names of files matching a pattern.
GetParent() Returns the parent directory for the specified path.
Move() Moves a directory and its contents to a specified path.
31
Directory Class
Method Description
Delete( ) Deletes a directory.
Exists() Determines if a directory exists.
GetFiles() Returns the names of files in a specified directory.
GetCurrentDirectory() Returns the path of the current directory.
GetLastAccessTime() Returns the last time file was accessed.
GetLastWriteTime() Returns the last time file was written.
32
DirectoryInfoClass
Method Description
Attributes Inherits from FileSystemInfo; gets or sets the
attributes of the current file.
CreationTime gets or sets the creation time of the current file.
Exists true if the directory exists.
Extension The File Extension
FullName the full path of the file or directory.
Name The directory name.
Root Root portion of the path.
Parent Parent Directory
33
DirectoryInfo Class
Method Description
Create() Creates the directory if it does not exist.
CreateSubdirectory() Creates a subdirectory.
Delete() Deletes the directory.
GetDirectories() Returns an array of DirectoryInfo objects.
GetFiles() Returns an array of FileInfo objects.
MoveTo() Relocates the directory and its contents.
Refresh() Refreshes the directory list.
* See FileDemo
34
A File Lister
string curDirName = Directory.GetCurrentDirectory();DirectoryInfo curInfo = new DirectoryInfo(curDirName);Console.WriteLine("Listing for {0}", curInfo.FullName);DirectoryInfo[] dlist = curInfo.GetDirectories();foreach (DirectoryInfo d in dlist) { Console.WriteLine("{0}\t\t{1}", d.Name,
d.LastWriteTime);}FileInfo[] flist = curInfo.GetFiles();foreach (FileInfo f in flist) { Console.WriteLine("{0}\t\t{1}", f.Name,
f.LastWriteTime);}
35
Working with Files
Two classes are provided to deal with filesFile
A collection of static methods to manipulate filesFileInfo
Instance methods to manipulate a single file
These classes are analogous to the two directory classes
They add the ability to read and write files
36
Reading and Writing Files
Files can be read and written in two waysBinary
Binary data is written to a file Fast, efficient, not human readable Suited for writing data structures
Text Converts bytes to a specific character encoding Slower than binary Can be read by humans
37
Stream Class
The Stream class is used to read and write binary data from and to a file
Read methods int Read(byte[] buf, int offset, int count)
Reads up to count bytes into buf at offset Return the number of bytes read or zero at EOF
int ReadByte() Reads one byte Returns -1 at EOF
38
Stream Class
Write methods void Write(byte[] buf, int offset, int count) void WriteByte(byte); void Flush();
Direct Access Methodslong Seek(long offset, SeekOrigin);
39
SeekOrigin
An enumeration with values indicating where a seek should be fromBegin, Current, End
Seeking moves the read/write pointer through a file and determines where the next read or write will occur
40
StreamReader Class
This reads a file by converting the bytes to characters int Read()
Reads the next char, returns -1 on EOF int Read(char[] buf, int offset, int count)
Reads up to count chars into buf at offset Return 0 at EOF
string ReadLine() Reads the next line Returns null on EOF
41
StreamWriter Class
Used to write text filesvoid Write(char)void Write(char[])void Write(string)Void Flush()
42
Buffered Streams
Read and writing a byte at a time is painfully slow
It is much more efficient to read and write a buffer full at a time
The BufferedStream class does just that It works just like a stream Just wrap it around your stream
BufferedStream bs = new BufferedStream(stream);
43
Opening Binary Streams
Open one stream for reading and one for writing
Use the static methods of the File classStream OpenRead(string path);Stream OpenWrite(string path);
44
Reading and Writing Text Files
To create a file for writingStreamWriter sw = new StreamWriter("MyFile.txt");
To open a file for readingFileInfo fi = new FileInfo("MyFile.txt");
StreamReader sr = fi.OpenText();
45
Reading and Writing Text Files
The following exampleChecks to see if a file exists If it does not, it opens the file for writing and
writes some content It then opens the file for reading and writes
the contents to the console It then closes the file
46
Read/Write Example
if (! File.Exists("MyFile.txt")) { StreamWriter sw = new StreamWriter("MyFile.txt"); sw.WriteLine("Line 1"); sw.WriteLine("Line 2"); sw.WriteLine("Line 3"); sw.Close();}FileInfo fi = new FileInfo("MyFile.txt");StreamReader sr = fi.OpenText();string line;while ((line = sr.ReadLine()) != null) { Console.WriteLine(line);}sr.Close();fi.Delete();
48
Delegates
A delegate is A single function pointerA collection of pointer to the same type of
function It is simply a variable which can hold one
or more pointers to functions In C and C++ these are known as
callbacks
49
Delegates
In may programming tasks you want to perform an action but want that action to be flexible
This means you want the client of your class to provide the action, yet you want to invoke it
There are a couple of solutions to this problem
50
The Visitor Pattern
You are writing a container class You want clients to be able to perform some
action on every element of your container You do not want them to know how your class is
implemented So, how do you let them visit every element in a
container without knowing how the container is implemented?
51
The Delegate Pattern
The delegate pattern says that you want to perform a logical action but leave the implementation to be specified at run-time
Therefore, you create a delegate and call it At run-time, the delegate is assigned the value
of a real function Thus, when you call the delegate, you actually
call the function assigned at run time
52
Implementing the Delegate Pattern
A delegate can be used to solve the vistor pattern
But how do you implement a delegate? In C/C++ use a function pointer In Java use an interface In C# use the special delegate type
53
The Interface Solution
To implement a solution to the visitor pattern using interfaces First declare an interface
public interface Visitor {
void Visit(object obj);
}Then create a class which implements the
Visitor interface
54
The Interface Solution
public class PrintVisitor: Visitor {
void Visit(object obj) {
Console.WriteLine(obj);
}
}The final step is to create a container class
which will provide a method to visit all of the elements it contains and invoke the visitor
55
The Interface Solution
public class MyArray {int[] ar;
public MyArray(int sz) {ar = new int[sz];
}
public void VisitElements(Visitor v) {foreach(int i in ar)
v.Visit(i);}
}
56
The Interface Solution
This just leaves writing the code to bring it all together
MyArray ar1 = new MyArray(10);
// put something in the array
ar1.VisitElements(new PrintVisitor());
57
Now, Back to Delegates
C# lets you declare a delegate as something which can be associated with one or more functions with the same signature and return type public delegate void ArrayVisitor( object o);
This declares a delegate Called ArrayVisitor Which accepts a single object parameter And returns void
58
Creating a Delegate
Begin by creating a method with the required signature and return typepublic void printer(object o) {
Console.WriteLine(o);}
Then, create a delegate from itArrayVisitor v1 = new ArrayVisitor(printer);
59
Using a Delegate
OK, so now that we have a delegate, how do we use it?
object[] ar = new object[5];
// put some values in the array
foreach(object obj in ar)
v1(obj);
60
Multicast Delegates
So far we can invoke one method when we invoke a delegate
What if we wanted to be able to do more than what one method could do?
We could have a delegate which could invoke several methods when it was invoked!
This is called a multicast delegate
61
Multicast Delegates
Declare a multicast delegateArrayVisitor multiVisitor;
Now, assign a method to itmultiVisitor = new ArrayVisitor(printer);
And then add anothermultiVisitor += new ArrayVisitor(printer1);
Now, when multiVisitor is invoked, it will invoke both printer and printer1
62
Multicast Delegates
You can add as many delegates as you like to a multicast delegate
You can remove a delegate from a multicast delegate by subtracting it
ArrayVisitor multiVisitor, v1, v2;v1 = new ArrayVisitor(printer);v2 = new ArrayVisitor(printer1);multiVisitor = v1;multiVisitor += v2;multiVisitor -= v1;
* see VisitableArray
63
Event Handling
GUI programming is event driven When a button is clicked, an event is generated This event is dispatched to any listeners who
have registered an interest in the event This is called the observer pattern or publish and
subscribe Delegates are used to implement lists of event
handlers in .NET GUI programming