Download presentation
Presentation is loading. Please wait.
Published byWhitney Rice Modified over 8 years ago
1
Fundamentals of.NET NYU-SCPS
2
Session 6 Exception Handling Exception Handling Streams Streams Files and Directories Files and Directories Working with Files Working with Files Modifying Files Modifying Files Reading and Writing Data Reading and Writing Data Binary Files/Text Files Binary Files/Text Files Asynchronous Asynchronous Building Windows Applications Building Windows Applications Creating a Simple Windows Form Creating a Simple Windows Form Using the Visual Studio.NET Designer Using the Visual Studio.NET Designer Creating a Windows Forms Application Creating a Windows Forms Application Populating the TreeView Controls Populating the TreeView Controls Handling TreeView events Handling TreeView events Deployment Projects Deployment Projects Setup Project Setup Project
3
Streams Pipe or a sequence of bytes representing a store Pipe or a sequence of bytes representing a store Has a “backing store” where bytes come from, or where bytes go to Has a “backing store” where bytes come from, or where bytes go to Disk file Disk file Network connection (socket) Network connection (socket) Block of memory (buffer) Block of memory (buffer) String String 01234567890123456789 File test.dat Stream of bytes Program That reads Or writes File test.dat read write
4
Stream Classes Stream Abstract base class that supports reading and writing bytes BinaryReader/BinaryWriter Read and write encoded strings and primitive data types to and from streams File, FileInfo Directory, DirectoryInfo Provide implementations for FileSystemInfo class, that support creating, moving, renaming and deleting files and directories FileStream For reading and writing to disk files TextReader, TextWriter StrringReader, StringWriter Support reading of unicode characters. BufferedStream Adds buffering capability to other streams such as NetworkStream MemoryStream Nonbufferred stream with a memory based store NetworkStream Stream over a socket GZipStream, DeflateStream Support compressed data CryptoStream, AuthenticatedStream, SslStream Specialized stream classes for encrypted files and network connections
5
Streams in C# BufferedStream System.IO FileStreamMemoryStreamNetworkStreamCryptoStream Stream FileSystemInfo DirectoryInfoFileInfo File Directory
6
Stream class Is an abstract base class Is an abstract base class Has raw, low-level read/write methods that read 8-bin bytes regardless of what’s in the store Has raw, low-level read/write methods that read 8-bin bytes regardless of what’s in the store Has methods to support basic stream operations: Has methods to support basic stream operations: Read data – read methods Read data – read methods Write data – write methods Write data – write methods Seek to a position in stream – seek method Seek to a position in stream – seek method Close and dispose a stream – flush, close and dispose Close and dispose a stream – flush, close and dispose Asynchronous I/O – beginread, endread, beginwrite, endwrite methods Asynchronous I/O – beginread, endread, beginwrite, endwrite methods
7
Readers and Writers System.IO TextReader StreamReaderStringReader TextWriter StreamWriterStringWriter
8
TextReader and TextWriter Read and write 8-bit UTF-8 unicode characters Read and write 8-bit UTF-8 unicode characters Supports multiple character encoding formats Supports multiple character encoding formats Adds convenience methods to deal with lines of text – readLine, writeLine Adds convenience methods to deal with lines of text – readLine, writeLine
9
BinaryReader and BinaryWriter Read and write binary data Read and write binary data Allows reading/writing primitive data types Allows reading/writing primitive data types Provide ReadT and WriteT methods where T is any primitive data type such as Byte, Boolean, Int32… Provide ReadT and WriteT methods where T is any primitive data type such as Byte, Boolean, Int32…
10
Files and Directories File and FileInfo provide methods to manipulate files File and FileInfo provide methods to manipulate files Directory and DirectoryInfo provide methods to manipulate directories Directory and DirectoryInfo provide methods to manipulate directories File class has methods to open a file for read or write and return a stream File class has methods to open a file for read or write and return a stream File may be opened in any of several modes – OpenOrCreate, Create, CreateNew, Open, Append, Truncate File may be opened in any of several modes – OpenOrCreate, Create, CreateNew, Open, Append, Truncate
11
File System Management File, FileInfo, Directory, DirectoryInfo classes also support file system management functions such as copying, moving, deleting files and directories File, FileInfo, Directory, DirectoryInfo classes also support file system management functions such as copying, moving, deleting files and directories ExploreDirectory Example ExploreDirectory Example Watching File System events example Watching File System events example
12
Files and Directories C# class File represents a file in the file system and the class Directory represents a folder in the file system. C# class File represents a file in the file system and the class Directory represents a folder in the file system. Use File and Directory for file maintenance tasks such as creating, deleting, copying and moving files or directories Use File and Directory for file maintenance tasks such as creating, deleting, copying and moving files or directories FileInfo has information about File and DirectoryInfo has information about Directory FileInfo has information about File and DirectoryInfo has information about Directory Use FileInfo and DirectoryInfo to get information such as last access time, last write time, size, name etc. Use FileInfo and DirectoryInfo to get information such as last access time, last write time, size, name etc.
13
Directory class members CreateDirectory - creates a directory CreateDirectory - creates a directory GetLastAccessTime and SetLastAccessTime -get and set last access time GetLastAccessTime and SetLastAccessTime -get and set last access time Delete – deletes a directory Delete – deletes a directory Move – moves a directory Move – moves a directory GetDirectories – gets a list of subdirectories GetDirectories – gets a list of subdirectories GetFiles – gets a list of files GetFiles – gets a list of files GetFileSystemEntries – gets a list of files & directories GetFileSystemEntries – gets a list of files & directories GetLogicalDrives – gets a list of logical drives GetLogicalDrives – gets a list of logical drives
14
DirectoryInfo class properties Attributes – attributes such as read-only, hidden etc. Attributes – attributes such as read-only, hidden etc. CreationTime – time the directory was created CreationTime – time the directory was created LastAccessTime – time it was last accessed LastAccessTime – time it was last accessed LastWriteTime – time it was last written to LastWriteTime – time it was last written to Extension – extension if any Extension – extension if any FullName - complete path name of this directory FullName - complete path name of this directory Name – name of this directory Name – name of this directory Parent – parent directory Parent – parent directory Root – root directory Root – root directory
15
DirectoryInfo class methods Create – creates a directory Create – creates a directory CreateSubdirectory – creates a subdirectory CreateSubdirectory – creates a subdirectory Delete – deletes this file Delete – deletes this file GetDirectories – gets a list of directories GetDirectories – gets a list of directories GetFiles – gets a list of files GetFiles – gets a list of files GetFileSystemInfos – gets a list of dir entries GetFileSystemInfos – gets a list of dir entries MoveTo – move this file to a new location MoveTo – move this file to a new location Refresh – refresh from disk Refresh – refresh from disk
16
private void ExploreDirectory(DirectoryInfo dir) { indentLevel++; // push a directory level // create indentation for subdirectories for (int i = 0; i < indentLevel; i++) Console.Write(" "); // two spaces per level // print the directory and the time last accessed Console.WriteLine("[{0}] {1} [{2}]\n", indentLevel, dir.Name, dir.LastAccessTime); // get all the directories in the current directory // and call this method recursively on each DirectoryInfo[] directories = dir.GetDirectories( ); foreach (DirectoryInfo newDir in directories) { dirCounter++; // increment the counter ExploreDirectory(newDir); } indentLevel--; // pop a directory level }
17
File class members AppendText – used to append text to this file AppendText – used to append text to this file Copy – copy this file to another file Copy – copy this file to another file Create – create a file Create – create a file CreateText – create a text file CreateText – create a text file Delete – delete this file Delete – delete this file Move – move this to another file Move – move this to another file Open – open this file I/O Open – open this file I/O OpenRead – open for reading OpenRead – open for reading OpenText – open a text file for reading OpenText – open a text file for reading
18
FileInfo class properties Attributes –attributes of this file Attributes –attributes of this file CreationTime – time this file was created CreationTime – time this file was created Directory – returns an instance of Directory for the folder this file resides in Directory – returns an instance of Directory for the folder this file resides in DirectoryName – returns the name of the dir DirectoryName – returns the name of the dir FullName – full path name FullName – full path name LastAccessTime – last time this file was accessed LastAccessTime – last time this file was accessed Length – size of this file Length – size of this file Name – name of this file Name – name of this file
19
FileInfo class methods AppendText – returns a StreamWriter to append text to this file AppendText – returns a StreamWriter to append text to this file CopyTo – copies to a new file CopyTo – copies to a new file Create – creates a file Create – creates a file CreateText – Creates a new text file CreateText – Creates a new text file Delete – delete this file Delete – delete this file MoveTo – move it to a new location MoveTo – move it to a new location Open – open this file Open – open this file OpenRead – open it for reads OpenRead – open it for reads OpenWrite – open it for writes OpenWrite – open it for writes
20
private void ExploreDirectory(DirectoryInfo dir) { indentLevel++; // push a directory level // create indentation for subdirectories for (int i = 0; i < indentLevel; i++) Console.Write(" "); // two spaces per level // print the directory and the time last accessed Console.WriteLine("[{0}] {1} [{2}]\n", indentLevel, dir.Name, dir.LastAccessTime); // get all the files in the directory and // print their name, last access time, and size FileInfo[] filesInDir = dir.GetFiles( ); foreach (FileInfo file in filesInDir) { // indent once extra to put files // under their directory for (int i = 0; i < indentLevel+1; i++) Console.Write(" "); // two spaces per level Console.WriteLine("{0} [{1}] Size: {2} bytes", file.Name, file.LastWriteTime, file.Length); fileCounter++; } // get all the directories in the current directory // and call this method recursively on each DirectoryInfo[] directories = dir.GetDirectories( ); foreach (DirectoryInfo newDir in directories) { dirCounter++; // increment the counter ExploreDirectory(newDir); } indentLevel--; // pop a directory level }
21
Reading & Writing Reading and writing is accomplished using Stream classes Reading and writing is accomplished using Stream classes BinaryReader and BinaryWriter classes treat files as a stream of binary characters BinaryReader and BinaryWriter classes treat files as a stream of binary characters TextReader and TextWriter classes treat files as lines of text and provide methods such as ReadLine, WriteLine TextReader and TextWriter classes treat files as lines of text and provide methods such as ReadLine, WriteLine
22
Stream class properties CanRead – true if it is possible to read from this stream CanRead – true if it is possible to read from this stream CanWrite – true if it is possible to write to this stream CanWrite – true if it is possible to write to this stream CanSeak – true if it is possible to seek CanSeak – true if it is possible to seek Length – length of the stream Length – length of the stream Position – get or set the current position in the stream Position – get or set the current position in the stream
23
Stream class methods Read – read a sequence of bytes Read – read a sequence of bytes Seek – seek to a specific position Seek – seek to a specific position Write – write a sequence of bytes Write – write a sequence of bytes Flush – flush buffers related to this stream Flush – flush buffers related to this stream BeginRead – begin asynchronous read BeginRead – begin asynchronous read BeginWrite – begin asynchronous write BeginWrite – begin asynchronous write
24
Stream class methods Read – read a sequence of bytes Read – read a sequence of bytes Seek – seek to a specific position Seek – seek to a specific position Write – write a sequence of bytes Write – write a sequence of bytes Flush – flush buffers related to this stream Flush – flush buffers related to this stream BeginRead – begin asynchronous read BeginRead – begin asynchronous read BeginWrite – begin asynchronous write BeginWrite – begin asynchronous write
25
class Tester { const int SizeBuff = 1024; public static void Main() { // the file to read from Stream inputStream = File.OpenRead( @"C:\test\source\test1.cs“ ); // the file to write to Stream outputStream = File.OpenWrite( @"C:\test\source\test1.bak“ ); // create a buffer to hold the bytes byte[] buffer = new Byte[SizeBuff]; int bytesRead; // while the read method returns bytes // keep writing them to the output stream while ( (bytesRead = inputStream.Read(buffer,0,SizeBuff)) > 0 ) { outputStream.Write(buffer,0,bytesRead); } // tidy up before exiting inputStream.Close(); outputStream.Close(); }
26
StreamReader and StreamWriter To read and write text files you should use instances of StreamReader and StreamWriter. To read and write text files you should use instances of StreamReader and StreamWriter. Use OpenText method in File or FileInfo class to create a Reader to read the file Use OpenText method in File or FileInfo class to create a Reader to read the file Use StreamWriter constructor to create a new writer to write to a file Use StreamWriter constructor to create a new writer to write to a file
27
StreamReader members Peek – allows look ahead Peek – allows look ahead Read – read from file Read – read from file ReadLine – read a line from file ReadLine – read a line from file ReadToEnd – reads till end of file ReadToEnd – reads till end of file
28
StreamWriter members AutoFlush property – indicates auto flush AutoFlush property – indicates auto flush Write – method to write data Write – method to write data WriteLine – method to write a line WriteLine – method to write a line Flush – method to flush the buffers to disk Flush – method to flush the buffers to disk
29
class Tester { public static void Main() { FileInfo theSourceFile = new FileInfo( @"C:\test\source\test.cs"); // create a text reader for that file StreamReader reader = theSourceFile.OpenText(); // create a text writer to the new file StreamWriter writer = new StreamWriter( @"C:\test\source\test.bak",false); // create a text variable to hold each line string text; // walk the file and read every line // writing both to the console // and to the file do { text = reader.ReadLine(); writer.WriteLine(text); Console.WriteLine(text); } while (text != null); // tidy up reader.Close(); writer.Close(); }
30
Isolated Storage A mechanism to store data while running as a least-privileged user – isolated storage is a “safe” place to store information without needing to resort to having users grant access to specific files or folders in the file system A mechanism to store data while running as a least-privileged user – isolated storage is a “safe” place to store information without needing to resort to having users grant access to specific files or folders in the file system IsolatedStorageFile class provides the basic functionality to create files and folders in isolated storage IsolatedStorageFile class provides the basic functionality to create files and folders in isolated storage
31
How to create a store Assembly/Machine – this creates a store to keep information that is specific to the calling assembly and the local machine – application- level data Assembly/Machine – this creates a store to keep information that is specific to the calling assembly and the local machine – application- level data Assembly/User – this method creates a store to keep information that is specific to the calling assembly and the current user – user-level data. Assembly/User – this method creates a store to keep information that is specific to the calling assembly and the current user – user-level data.
32
IsolatedStorageFile methods GetMachineStoreForApplication Retrieves machine-level store for calling app GetMachineStoreForAssembly Retrieves a machine-level store for asssembly GetMachineStoreForDomain Retrieves a machine-level store for the AppDomain GetStore Retrieves stores based on the scope provided GetUserStoreForApplication Retrieves a user-level store for the app GetUserStoreForAssembly Retrieves a user-level store for the assembly GetUserStoreForDomain Retrieves a user-level store for the AppDomain
33
class IsolatedFileTest { public static void Main() { IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly(); IsolatedStorageFileStream userStream = new IsolatedStorageFileStream(“UserSettings.set”, FileMode.Create, userStore); StreamWriter userWriter = new StreamWriter(userStream); userWriter.WriteLine(“User Prefs”); userWriter.Close(); // using directories userStore.CreateDirectory(“Fonts”); IsolatedStorageFileStream fontStream = new IsolatedStorageFileStream(“Fonts\fontlist.set”), FileMode.Create, userStore); // checking if a file exists string[] files = userStore.GetFileNames(“UserSettings.set”); if( files.Length == 0 ) { Console.WriteLine(“no data saved for this user”); } else { IsolatedStorageFileStream settingStream = new IsolatedStorageStream(files[0], FileMode.Open, userStore); StreamReader settingReader = new StreamReader(settingStream); String prefs = settingReader.ReadLine(); }
34
Asynchronous I/O Stream classes supports asynchronous I/O through the methods BeginRead and BeginWrite. Stream classes supports asynchronous I/O through the methods BeginRead and BeginWrite. BeginRead begins reading and calls a method through a delegate that you pass to notify when the read is completed BeginRead begins reading and calls a method through a delegate that you pass to notify when the read is completed Similarly BeginWrite takes a method delegate to call back when write is completed. Similarly BeginWrite takes a method delegate to call back when write is completed.
35
public class AsynchIOTester { private Stream inputStream; // delegated method private AsyncCallback myCallBack; // buffer to hold the read data private byte[] buffer; // the size of the buffer const int BufferSize = 256; // constructor AsynchIOTester() { // open the input stream inputStream = new FileStream( @"C:\test\streams.txt", // the file to open FileMode.Open, // how to open the file FileAccess.Read, // how the file can be accessed FileShare.Read, // file share 1024, // buffer size in bytes true // set asynch to true (default is false) ); // allocate a buffer buffer = new byte[BufferSize]; // assign the call back myCallBack = new AsyncCallback(this.OnCompletedRead); }
36
public static void Main() { // create an instance of AsynchIOTester // which invokes the constructor AsynchIOTester theApp = new AsynchIOTester(); // call the instance method theApp.Run(); } void Run() { inputStream.BeginRead( buffer, // holds the results 0, // offset buffer.Length, // (BufferSize) myCallBack, // call back delegate null); // local state object // do some work while data is read for (long i = 0; i < 500000; i++) { if (i%1000 == 0) { Console.WriteLine("i: {0}", i); } }
37
// call back method void OnCompletedRead(IAsyncResult asyncResult) { int bytesRead = inputStream.EndRead(asyncResult); // if we got bytes, make them a string // and display them, then start up again. // Otherwise, we're done. if (bytesRead > 0) { String s = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine(s); inputStream.BeginRead( buffer, 0, buffer.Length, myCallBack, null); }
38
IO Completion Ports Using Win32 APIs you can set up a thread that will wake up when IO operation completes Using Win32 APIs you can set up a thread that will wake up when IO operation completes.NET exposes similar API with the ThreadPool class.NET exposes similar API with the ThreadPool class
39
Standard Devices Standard Input is keyboard input Standard Input is keyboard input Standard Output is output to console window Standard Output is output to console window Standard Error, by default, is output to console window Standard Error, by default, is output to console window.NET standard devices are.NET standard devices are TextWriter Out TextWriter Out TextWriter Error TextWriter Error TextReader In TextReader In To Redirect – use SetOut, SetError, SetIn To Redirect – use SetOut, SetError, SetIn
40
Writing to Standard Out Console.Out is the standard output stream Console.Out is the standard output stream Console.Error is the standard error stream Console.Error is the standard error stream Console.In is the standard input stream Console.In is the standard input stream Use Write, or WriteLine to output to screen Use Write, or WriteLine to output to screen Use Read, ReadLine to read keyboard input Use Read, ReadLine to read keyboard input Some other interesting methods in Console Some other interesting methods in Console
41
Serial Ports System.IO.Ports namespace provides functionality similar to Standard Input and Output to communicate over Serial Ports System.IO.Ports namespace provides functionality similar to Standard Input and Output to communicate over Serial Ports Create an instance of SerialPort and “Open” it before communicating Create an instance of SerialPort and “Open” it before communicating Use methods Read, ReadByte, ReadChar, ReadLine to read from the serial port Use methods Read, ReadByte, ReadChar, ReadLine to read from the serial port Use methods Write, WriteByte, WriteChar, WriteLine to write to the serial port Use methods Write, WriteByte, WriteChar, WriteLine to write to the serial port
42
Networking System.Net, System.Net.Mail, System.Net.Mail, System.Net.Sockets and other System.Net.* namespaces have classes that are together known as “Networking Class Libraries” System.Net, System.Net.Mail, System.Net.Mail, System.Net.Sockets and other System.Net.* namespaces have classes that are together known as “Networking Class Libraries” Basic mechanism of communications over a network is “Sockets” Basic mechanism of communications over a network is “Sockets” More advanced communication technologies include inter-program Messaging providers such as MSMQ, TIBCO EMS, TIBCO RV etc. More advanced communication technologies include inter-program Messaging providers such as MSMQ, TIBCO EMS, TIBCO RV etc.
43
ISO stack and TCP/IP stack Application Presentation Session Transport Network Data Link Physical Application Transport (TCP & UDP) Internet (IP) Network Interface ISO Reference Model TCP Reference Model
44
Network Communications Application Transport Internet Network Interface Application Transport Internet Network Interface Machine AMachine B
45
Sockets and Ports Source ip Source port Destination ip Destination port
46
TCP/IP Session Source machine creates a socket and attempts to connect to a destination machine by giving its “ip” and “port” numbers Source machine creates a socket and attempts to connect to a destination machine by giving its “ip” and “port” numbers Source machine responds with ConnectionAccepted Source machine responds with ConnectionAccepted If the destination machine is listening on that port “and” accepts this connection it responds with “request accepted” If the destination machine is listening on that port “and” accepts this connection it responds with “request accepted” Data can now be transferred until an EOF is seen or a Network Error occurs
47
Common Socket Terms Binding: before listening for data from a socket a process must “bind” to a specific “IP” and a specific “port” Binding: before listening for data from a socket a process must “bind” to a specific “IP” and a specific “port” Listen: refers to the state when a program is waiting to “hear” something on the port Listen: refers to the state when a program is waiting to “hear” something on the port Accept: an operation that must be performed by the “listening” socket before data will be read Accept: an operation that must be performed by the “listening” socket before data will be read Connect: sends a connect request to a “listener” Connect: sends a connect request to a “listener” Send: sends data over a connection Send: sends data over a connection Receive: receive data from a connection Receive: receive data from a connection Close: close the connection when done Close: close the connection when done
48
Steps to send data (client) Create A socket (client side) Create A socket (client side) Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) Connect to another socket (on the server) Connect to another socket (on the server) s.Connect(“<hostname”, portnumber) Send Data Send Data byte[] buffer = byte[] buffer = s.Send(buffer) Send Data (alternate method) Send Data (alternate method) NetworkStream ns = new NetworkStream(s) StreamWriter sw = new StreamWriter(ns, Encoding.UTF8)
49
Steps to receive data (server) Create A socket (server side) Create A socket (server side) Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) Bind to an IP and a Port Bind to an IP and a Port s.Bind(new IPEndPoint(IPAddress.Loopback, 9999) Accept incoming connections Accept incoming connections Socket client = s.Accept(); Receive Data Receive Data byte[] buffer = new byte[1024]; int bytesRead = s.Receive(buffer); Receive Data (alternate) Receive Data (alternate) NetworkStream ns = new NetworkStream(client) StreamReader sr = new StreamReader(ns, Encoding.UTF8)
50
Protocol Clients and Listeners TcpClient and TcpListener are wrappers over TCP Sockets TcpClient and TcpListener are wrappers over TCP Sockets UdpClient is a wrapper over a UDP socket UdpClient is a wrapper over a UDP socket WebClient and HTTPListener provide methods to make HTTP connections WebClient and HTTPListener provide methods to make HTTP connections SmtpClient class provides methods to talk to a SMTP server SmtpClient class provides methods to talk to a SMTP server Code examples of clients and listeners Code examples of clients and listeners
51
Serialization Is the process of converting the bytes that represent an Object into a form that may be persisted or transported Is the process of converting the bytes that represent an Object into a form that may be persisted or transported Binary serialization preserves type information along with the data Binary serialization preserves type information along with the data XML serialization only preserves data XML serialization only preserves data System.Runtime.Serilization namespace contains classes that may be used to serialize/deserialize System.Runtime.Serilization namespace contains classes that may be used to serialize/deserialize
52
Serialization Example public static void WriteToFile(Rectangle r, String filename) { Stream str = File.OpenWrite(filename); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(str, bp); str.Close();} public static void WriteToFile(Rectangle r, String filename) { Stream str = File.OpenWrite(filename); SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(str, shape); str.Close(); }
53
Formatters System.Runtime.Serializable.Formatter class provides the common functionality for serilization formatters System.Runtime.Serializable.Formatter class provides the common functionality for serilization formatters System.Runtime.Serializable.Formatters.Binary System.Runtime.Serializable.Formatters.Binary BinaryFormatter BinaryFormatter System.Runtime.Serializable.Formatters.SOAP System.Runtime.Serializable.Formatters.SOAP SOAPFormater SOAPFormater
54
DeSerialization Example public static void ReadFromFile(Rectangle r, String filename) { Stream str = File.OpenRead(filename); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(str, bp); str.Close();} public static void ReadFromFile(Rectangle r, String filename) { Stream str = File.OpenRead(filename); SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(str, shape); str.Close(); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.