I/O & OBJECT SERIALIZATION INTRODUCTION System.IO namespace has classes for manipulating file system & file data. Reading a file Writing to a file Dealing with File Attributes Dealing with Directories Dealing with Hard Disk Drives Dealing with Paths Serialization is the process to convert object data to different format so that one can store it to persistent storage. FILE SYSTEM CLASSES System.IO classes are of two categories Informational Classes Utility Classes Most informational classes are derived from FileSystemInfo base class. The informational classes provide information about file, directories & drives. Utility classes provide static methods to perform operations on files, directories & drives. FILESYSTEMINFO CLASS FileSystemInfo serves as the base class for both FileInfo and Directoryinfo classes. FileSystemInfo is a an abstract class. FileSystemInfo methods Delete Removes the file or directory from file system. Refersh Updates the data in the class with the most current information from file system. FILESYSTEMINFO PROPERTIES Name Gets the name of file or directory. FullName Gets the full path to the file or directory. Extension Get a string representation of extension part of file/directory. Exists Determines whether the file/directory exists. FILESYSTEMINFO PROPERTIES CreationTime Gets/sets the time the current file/directory was created. Attributes Gets/sets FileAttributes of the current file/directory. LastAccessTime Gets/sets the time the file/directory was accessed. LastWriteTime Gets/sets the time the file/directory was last written to. FILEINFO CLASS Properties Directory Retrieves a DirectoryInfo object that represents the directory in which the file is stored. DirectoryName Gets the name of directory in which the file is stored. IsReadOnly Determines if the file is read-only. Length Gets the length of the file. FILEINFO METHODS Open Opens the file with specified permission (read, write etc.) OpenText Opens the file & returns a StreamReader object to read contents of file. OpenWrite Opens the file with the write-only access. AppendText Returns a StreamWriter object to append the text. FILEINFO METHODS CopyTo Makes a copy a file in the new location. Create Creates a file based on the current file information. CreateText Returns a StreamWriter object with the new file created. MoveTo Moves the file to a new location. Replace Replaces a file with the information in the current FileInfo object. USING FILEINFO Dim inf As FileInfo = New FileInfo("C:\hello.txt") If inf.Exists Then Console.WriteLine("Name :" + inf.Name) Console.WriteLine("Extenstion:" + inf.Extension) Console.WriteLine("Directory Name:" + inf.DirectoryName) Console.WriteLine("Length:" + inf.Length.ToString()) inf.CopyTo(@"c:\hi.txt", true) End If DIRECTORYINFO CLASS Properties Parent Gets a DirectoryInfo object for the parent directory of the specified directory. Root Gets the root part of the directory’s path as a string. Methods Create Creates the directory with the current DirectoryInfo object information. DIRECTORYINFO METHODS CreateSubdirectory Creates a new child directory for the current directory. GetDirectories Retrieves an array of DirectoryInfo objects representing subdirectories of current directory. GetFiles Retrieves an array of FileInfo objects representing files in the current directory. GetFileSystemInfos Retrieves an array of FileSystemInfo objects representing files & subdirectories in the current directory. MoveTo Moves the current directory to the new location. USING DIRECTORYINFO Dim inf As DirectoryInfo = New DirectoryInfo("E:\Training\") If inf.Exists Then For Each finf As FileSystemInfo In inf.GetFileSystemInfos() Console.WriteLine("Full Name:" + finf.FullName) Next Console.WriteLine("Files in Directory " + inf.Name + ":") For Each finf As FileInfo In inf.GetFiles() Console.WriteLine(finf.Name) Next End If DRIVEINFO CLASS DriveInfo class allows to access & manipulate single drive of the file system. Method GetDrives A static method that returns all the drives on the current system. Properties AvailableFreeSpace Gets the amount of available (dependes on disk quotas) space on the drive. DRIVEINFO PROPERTIES DriveFormat Gets the format of drive such as NTFS, FAT32 etc. DriveType Gets the type of drive in the form of the DriveType enumeration. IsReady Gets the status of drive & tells if it is ready to access. Name Get the name of the drive. DRIVEINFO PROPERTIES RootDirectory Gets a DirectoryInfo object that represents the root directory of the drive. TotalFreeSpace Gets the total amount of free space on the drive. TotalSize Gets the total size of the drive. VolumeLabel Gets/sets a drive label. DRIVETYPE ENUMERATION CDRom An optical drive. It can be CD, DVD and so on. Fixed A fixed disk. Network A network mapped drive. NoRootDirectory A drive that does not have a root directory. DRIVETYPE ENUMERATION Ram A RAM drive. Removable A drive that has a removable media. Unknown The drive could not be determined. USING DRIVEINFO For Each inf As DriveInfo In DriveInfo.GetDrives() If inf.IsReady Then Console.WriteLine(inf.Name + " Statistics") Console.WriteLine("Available Free Space: " + _ inf.AvailableFreeSpace.ToString() + " Bytes") Console.WriteLine("Total Free Space:" + _ inf.TotalFreeSpace.ToString() + " Bytes") Console.WriteLine("Total Space:" + _ inf.TotalSize.ToString() + " Bytes") End If Next PATH CLASS Allows to manipulate a file system path. Methods All methods are static. ChangeExtension Takes a path & returns a new path with the file name’s extension changed. Do not affect actual file system file. Combine Combines two compatible path strings. GetPathRoot Returns a root directory name in the specified path.0 PATH METHODS GetDirectoryName Returns the name of the directory in the specified path. GetExtension Returns the extension of the file from the specified path. GetFileName/ GetFileNameWithoutExtention Returns the name of the file from the specified path. GetFullPath Returns absolute path for a relative path. GetRandomFileName Generates a random file name. PATH METHODS GetTempFileName Generates a temporary file in the file system & returns the full path to the file. GetTempPath Returns path to the temporary file directory for the current user/system. HasExtension Indicates the specified path’s file name has an extension. IsPathRooted Determines if the specified is absolute path. USING PATH Console.WriteLine("File Without Extenstion:" + _ Path.GetFileNameWithoutExtension("C:\Training\book.doc")) Console.WriteLine("Random File:" + Path.GetRandomFileName()) Console.WriteLine("Temporary Path:" + Path.GetTempPath()) Console.WriteLine("File Extension:" + _ Path.GetExtension("C:\Training\book.doc")) Console.WriteLine("Path With Changed Extension:" + _ Path.ChangeExtension("C:\Training\book.doc", "xls")) Console.WriteLine("Path Combined:" + _ Path.Combine("C:\Training\", "book.doc")) Console.WriteLine("Path Rooted:" + _ Path.IsPathRooted("C:\Training\book.doc").ToString()) FILESYSTEMWATCHER CLASS Monitors file system directories for changes. Properties IncludeSubdirectories Specifies whether to monitor subdirectories or only the directory in path. NotifyFilter Gets/sets the type of changes to watch for. Default s all. Path Gets/sets the path to the directory to watch. FILESYSTEMWATCHER EVENTS Changed Fires when a file or directory is changed in the watched directory. Created Fires when a file/directory is created in the watched directory. Deleted Occurs when a file/directory has been deleted from the watched directory. Renamed Fires when a file/directory has been renamed in the watched directory. USING FILESYSTEMWATCHER Dim watch As FileSystemWatcher = new FileSystemWatcher() watch.Path = "C:\temp" watch.EnableRaisingEvents = True AddHandler watch.Created, New FileSystemEventHandler( _ AddressOf watch_Created) Sub watch_Created(ByVal sender As Object, ByVal e As _ FileSystemEventArgs) MessageBox.Show("New file/directory created. Name: "+e.Name) End Sub STREAMS .NET performs I/O through streams. A stream is an abstraction that either produces or consumes information. The System.IO.Stream base class provides a common abstract interface to all streams in Framework. Each stream has a single data source, representing a backing store of bytes that can be read from or written to. STREAM PROPERTIES CanRead Determines if the stream supports reading. CanSeek Indicates if the stream supports seeking. CanWrite Determines if the stream supports writing. CanTimeout Determines if the stream can time out. STREAM PROPERTIES Length Gets the length in bytes of the stream. Position Gets/sets the virtual cursor for determining where in the stream the current positin is. ReadTimeout Gets/sets the stream’s timeout for read operations. WriteTimeout Gets/sets the stream’s timeout for write operations. STREAM METHODS Read Performs a sequential read of the specified number of bytes from current position & updates the virtual cursor to the end of read bytes. ReadByte Performs the read of a single byte & moves position by one byte forward. Seek Sets the position in the current stream. SetLength Specifies the length of the stream. If newLength<oldLength, truncates the file. STREAM METHODS Write Writes information to the stream as a number of bytes & updates the current position to reflect the new write position. WriteByte Writes a single byte to the stream & updates the new write to position. Flush Clears if any buffers in the stream & forces updation to be written to the underlying device. Close Closes the stream & releases the resources with it. STREAM CLASSES Classes derived from Stream class. FileStream (System.IO) MemoryStream (System.IO) NetworkStream(System.Net) GZipStream(System.Compression) FILESTREAM CLASS Provides facility to open a file for reading & writing. Properties Handle Gets the streams’ underlying file handle. Name Gets the name of the file. Methods Lock/UnLock DisAllows/allows other processes to change the file. STREAMREADER CLASS Provides facility to read data from Stream derived class. Reads characters rather than raw bytes. (Basic unit is character[2-bytes] not byte) Properties BaseStream Gets the underlying stream that the reader is reading. CurrentEncoding Gets the current encoding (character set) used for the uderlying stream. EndOfStream Determines if the reader has encountered the ed of the stream. STREAMREADER METHODS Close Closes the reader & the stream. Peek Returns the next character in the stream without updating the current position. Read/ReadBlock Reads the next set of characters in the stream. ReadLine Reads the next line of characters in the stream USING STREAMREDAER & FILESTREAM ReadToEnd Reads all characters through to the end of stream. Dim fs As FileStream = New FileStream("C:\hello.txt", FileMode.Open, _ FileAccess.Read) Dim sr As StreamReader = New StreamReader(fs) Dim str As String = sr.ReadToEnd() Console.WriteLine("File Name:" + fs.Name) Console.WriteLine(str) sr.Close() FILEMODE ENUMERATION Append Opens a file & moves the pointer in FileStream to the end of the file. Create Creates a new file. If already exists, overwrites. CreateNew Same as Create. If already exists, throws an exception. Open Opens an existing file. If file does not exist, exception occurs. OpenOrCreate Same as open. If file does not exist, creates a new file. Truncate Opens an existing file & empties it. STREAMWRITER CLASS Provides the functionality to write data to the Stream derived classes. Properties AutoFlush Gets/sets a flag specifying whether every call to Write should flush the changes to the underlying stream. NewLine Gets/sets a string that contains the line terminator string. STREAMWRITER METHODS Close Closes the writer & the underlying stream. Write Writes to the stream. WriteLine Writes the data to the stream with appended newline character. USING STREAMWRITER & FILESTREAM Dim fs As FileStream = New FileStream("C:\hello.txt", FileMode.Open, _ FileAccess.Read) Dim sr As StreamWriter = New StreamWriter(fs) Dim str As String = "Welcome to iConnect" sr.WriteLine(Str) sr.Close() Dim sr As StreamWriter = New StreamWriter("c:\hello.txt", True) Dim str As String = "Welcome to iConnect" sr.WriteLine(Str) sr.Close() FILE CLASS The File class provides the functions to open file streams for reading & writing. All methods are static Methods AppendAllText Appends a specified string into an existing file. If file does not exist, it creates the file. AppenText Opens an existing file & returns StreamWriter object which appends text to stream. If the does not exist, creates a new one. FILE METHODS Copy Copies a file to the new file. Throw an exception if new file exists. Create Creates a new file & returns a FileStream object. CreateText Creates or opens a file & returns a StreamWriter object. Move Moves a file from one location to other location. FILE METHODS Open/OpenRead Open an existing file & returns a FileStream object. OpenRead returns read-only FileStream. OpenText Opens an existing file & returns StreamReader object. OpenWrite Opens an existing file for writing & returns StreamWriter object. ReadAllBytes Opena a file, read its contents in a byte array & closes the file as an atomic operation. FILE METHODS ReadAllLines Opens a file, read its contents as an array of strings & close the file as an atomic operation. One string per line. ReadAllText Opens a file, read its contents in a string & closes the file as an atomic operation. WriteAllBytes/WriteAllLines/WriteAllText Opens a file, writes byte array/string array/string to the file & closes the file as an atomic operation. USING FILE CLASS If File.Exists("c:\hi.txt") Then File.Delete("c:\hi.txt") End If File.Copy("c:\hello.txt", "c:\hi.txt") Dim str() As String = File.ReadAllLines("c:\hi.txt") For Each ss As String In str Console.WriteLine(ss) Next Just like File class, there is Directory class with static methods to manipulate directories. BINARYWRITER/BINARYREADER CLASS BinaryWriter: Used to put binary data to stream. BinaryReader: Used to get binary data from stream. Non-text file such as Image are read/write in binary format. Dim fs As FileStream = New FileStream("C:\Image001.jpg", FileMode.Op Dim ds As FileStream = File.Create("c:\Image3.jpg") Dim br As BinaryReader = New BinaryReader(fs) Dim bb() As Byte = br.ReadBytes(CType(fs.Length, Integer)) Dim bw As BinaryWriter = New BinaryWriter(ds) bw.Write(bb) Code copies image br.Close() file. bw.Close() SERIALIZATION Applications requires that the data stored in object to be stored in persistent storage or to be transferred to other process. Object should be brought to proper format so that can be stored to or transferred. The process to convert object to different format is referred as Serialization. SERIALIZATION Serialization is implemented in namespace System.Runtime.Serialization. Serializing is a process to convert the object into a linear sequence of bytes that can be stored / transferred. Deserializing is the process of constructing an object from serialized object. SERIALIZABLE ATTRIBUTE The custom classes created can be made serializable i.e. we can serialize & deserialize their objects. Mark the class with attribute “Serializable”. To exclude particular member of custom class from serialization, Mark it with attribute “NonSerialized”. <Serializable()> Public Class Item Public ID As Integer Public price As Decimal Public quantity As Integer <NonSerialized()> Public total As Decimal Public Sub New(ByVal indx As Integer, ByVal _p As Decimal, _ ByVal q As Integer) ID = indx price = _p quantity = q total = quantity * price End Sub End Class SERIALIZING AN OBJECT Create a stream object to hold the serialized output. Create a BinaryFormatter object. Call Serialize method of BinaryFormatter object. Dim fs As FileStream = New FileStream("C:\Serial.data", FileMode.Create) Dim bf As BinaryFormatter = New BinaryFormatter() bf.Serialize(fs, DateTime.Now) fs.Close() DESERIALIZE AN OBJECT Create a stream object to read the serialized output. Create a BinaryFormatter object. Create a new object to save deserialized data. Call Deserialize method of BinaryFormatter object & cast o/p correct type. Dim fs As FileStream = New FileStream("C:\Serial.data", FileMode.Open Dim bf As BinaryFormatter = New BinaryFormatter() Dim obj As Object = bf.Deserialize(fs) Dim dt As Date = DirectCast(obj, Date) fs.Close() FORMATTER CLASSES BinaryFormatter Namespace: System.Runtime.Serialization.Formatters.Binar y Used to serialize object that will be read by .NET Framework application only. SoapFormatter Namespace:System.Runtime.Formatters.Soap XML-based Use if non-.NET applications are to read it. Passes through firewalls also.
Pages to are hidden for
"net vb IOSerialization"Please download to view full document