Input and Output 23: Input and Output Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Objectives Survey IO facilities in .NET Framework Class Library 23: Input and Output Objectives Survey IO facilities in .NET Framework Class Library file and directory management text files binary files object serialization Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
IO Library Input/output library in System.IO namespace 23: Input and Output IO Library Input/output library in System.IO namespace Support provided for: file and directory management text files binary files simple type conversion to/from binary Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
23: Input and Output Files and directories Two primary classes to work with files and directories perform file system interaction generally do not manipulate file contents derived from common base FileSystemInfo DirectoryInfo FileInfo Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
FileSystemInfo Files and directories have some operations in common 23: Input and Output FileSystemInfo Files and directories have some operations in common provided in base class FileSystemInfo public abstract class FileSystemInfo ... { public abstract string Name { get; } public string FullName { get; } public string Extension { get; } public abstract bool Exists { get; } public DateTime CreationTime { get; set; } public DateTime LastAccessTime { get; set; } public DateTime LastWriteTime { get; set; } public FileAttributes Attributes { get; set; } public void Delete() ... ... } name characteristics delete Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
DirectoryInfo DirectoryInfo represents a directory 23: Input and Output DirectoryInfo DirectoryInfo represents a directory methods provided to examine and manipulate inherits common operations from FileSystemInfo public sealed class DirectoryInfo : FileSystemInfo { public DirectoryInfo(string path) ... public DirectoryInfo Parent { get; } public DirectoryInfo Root { get; } public void Create () ... public void MoveTo (string destDirName) ... public void Delete (bool recursive ) ... public DirectoryInfo CreateSubdirectory(string path ) ... public FileInfo [] GetFiles () ... public DirectoryInfo [] GetDirectories () ... public FileSystemInfo[] GetFileSystemInfos() ... ... } constructor navigation manipulation contents Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
FileInfo FileInfo represents a file 23: Input and Output FileInfo FileInfo represents a file methods provided to examine and manipulate inherits common operations from FileSystemInfo public sealed class FileInfo : FileSystemInfo { public FileInfo(string fileName) ... public long Length { get; } public string DirectoryName { get; } public DirectoryInfo Directory { get; } public FileInfo CopyTo(string destFileName) ... public FileInfo CopyTo(string destFileName, bool overwrite) ... public void MoveTo(string destFileName) ... ... } constructor length location manipulation Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Application: List contents 23: Input and Output Application: List contents Can examine contents of a directory void List(string path) { DirectoryInfo directory = new DirectoryInfo(path); FileInfo [] files = directory.GetFiles (); DirectoryInfo[] directories = directory.GetDirectories(); foreach (FileInfo f in files) Console.WriteLine(f.Name); foreach (DirectoryInfo d in directories) Console.WriteLine(d.Name); } contents files directories Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Application: Find file 23: Input and Output Application: Find file Can search file system to find specified files void Find(string filename, DirectoryInfo root, ArrayList results) { foreach (FileInfo f in root.GetFiles(filename)) results.Add(f.FullName); foreach (DirectoryInfo d in root.GetDirectories()) Find(filename, d, results); } search with pattern recursive call for each subdirectory DirectoryInfo root = new DirectoryInfo(@"C:\WINDOWS"); ArrayList results = new ArrayList(); Find("mscoree.dll", root, results); foreach (string s in results) Console.WriteLine(s); Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
23: Input and Output Utility classes Three utility classes also work with files and directories Path Directory File Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Path Path provides static methods to manipulate a path string 23: Input and Output Path Path provides static methods to manipulate a path string most do not interact with the file system public sealed class Path { public static bool HasExtension (string path) ... public static string GetExtension (string path) ... public static string ChangeExtension(string path, string extension) ... public static string GetDirectoryName(string path) ... public static string GetFileName (string path) ... public static string GetFileNameWithoutExtension(string path) ... public static readonly char DirectorySeparatorChar; public static readonly char VolumeSeparatorChar; public static readonly char PathSeparator; ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Application: parse path 23: Input and Output Application: parse path Path methods useful to parse path into constituent parts public void Parse(string path) { string a = Path.GetDirectoryName (path); string b = Path.GetFileName (path); string c = Path.GetFileNameWithoutExtension(path); string d = Path.GetExtension (path); string e = Path.GetPathRoot (path); ... } C:\WINDOWS\system32 mscoree.dll mscoree .dll C:\ string path = @"C:\WINDOWS\system32\mscoree.dll"; Parse(path); Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Directory Directory has static methods to manipulate directories 23: Input and Output Directory Directory has static methods to manipulate directories most have analogues in DirectoryInfo several offer unique functionality public sealed class Directory { public static string[] GetLogicalDrives() public static string GetCurrentDirectory() public static void SetCurrentDirectory(string path) public static bool Exists (string path) ... public static string[] GetFiles (string path) ... public static string[] GetDirectories(string path) ... public static void Delete (string path) public static void Move(string source, string dest) ... } all drives on system current directory similar methods in DirectoryInfo Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Application: examine drives 23: Input and Output Application: examine drives Can examine all logical drives use Directory.GetLogicalDrives to get drives use Directory.Exists to determine if disk in drive all drives string[] drives = Directory.GetLogicalDrives(); foreach (string s in drives) { if (Directory.Exists(s)) ... } disk in drive? Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
File File has static methods to manipulate files 23: Input and Output File File has static methods to manipulate files all have analogues in FileInfo public sealed class File { public static bool Exists(string path) ... public static void Delete(string path) ... public static void Copy (string source, string dest) ... public static void Move (string source, string dest) ... ... } similar methods in FileInfo Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Choice of file / directory class 23: Input and Output Choice of file / directory class Must sometimes decide which class to use File vs. FileInfo Directory vs. DirectoryInfo Static methods can offer more convenient usage syntax require permission check on each call Instance methods must instantiate object some permission checks can be done once in constructor Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
File contents manipulation 23: Input and Output File contents manipulation Classes provided to manipulate file contents separate classes for text and binary files filters convert simple types to/from bytes for binary storage support for disk or memory files Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Character IO Classes provided to do character IO 23: Input and Output Character IO Classes provided to do character IO most methods defined in base classes derived classes specialized for data location and operation TextReader TextWriter StreamWriter StringWriter StreamReader StringReader write to disk write to StringBuilder read from disk read from string Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
StreamWriter StreamWriter writes characters to text file 23: Input and Output StreamWriter StreamWriter writes characters to text file open file with one of many constructors write with overloaded Write / WriteLine methods close automatically converted to string using ToString char, bool, string, short, int, long, float, double, etc. text file open StreamWriter sw = new StreamWriter("Chores.txt"); int n = 3; sw.WriteLine("Go to pet store"); sw.Write("Feed all "); sw.Write(n); sw.WriteLine(" cats"); sw.Close(); write close Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
StreamReader StreamReader reads characters from text file 23: Input and Output StreamReader StreamReader reads characters from text file open file with one of many constructors read characters or strings with Read / ReadLine methods close can read only char or string char, string text file open StreamReader sr = new StreamReader("Chores.txt"); string s; while ((s = sr.ReadLine()) != null) Console.WriteLine(s); sr.Close(); read close Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Byte IO Classes provided to do byte IO 23: Input and Output Byte IO Classes provided to do byte IO most methods defined in base class Two possible data locations provided in System.IO disk memory Stream FileStream MemoryStream read/write disk read/write byte array Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Stream methods Stream offers extensive functionality 23: Input and Output Stream methods Stream offers extensive functionality read / write bytes random access asynchronous read / write public abstract class Stream ... { public virtual int ReadByte () ... public virtual void WriteByte(byte value) ... public abstract int Read (byte[] buffer, int offset, int count); public abstract void Write(byte[] buffer, int offset, int count); public abstract long Seek (long offset, SeekOrigin origin); public abstract long Position { get; set; } public virtual IAsyncResult BeginRead (...) ... public virtual int EndRead (...) ... public virtual IAsyncResult BeginWrite(...) ... public virtual void EndWrite (...) ... ... } read/write random access asynch Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
FileStream FileStream supports read / write bytes to disk file open 23: Input and Output FileStream FileStream supports read / write bytes to disk file open FileStream f = new FileStream ( "Bytes.dat", FileMode.Create, FileAccess.ReadWrite ); f.WriteByte((byte)10); f.WriteByte((byte)20); f.WriteByte((byte)30); f.WriteByte((byte)90); f.WriteByte((byte)50); f.Seek(-2, SeekOrigin.Current); f.WriteByte((byte)40); f.Seek(0, SeekOrigin.Begin); int b = f.ReadByte(); f.Close(); byte, byte[] binary file write back up 2 bytes back up to beginning close Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Simple type output BinaryWriter converts many core types to binary 23: Input and Output Simple type output BinaryWriter converts many core types to binary must be used with a stream for storage Write methods convert and write bytes to backing stream char, bool, string, short, int, long, float, double, etc. simple types converter bytes binary file data store FileStream data = new FileStream("Bytes.dat", FileMode.Create); BinaryWriter converter = new BinaryWriter(data); converter.Write(17); converter.Write(3.14); converter.Write("hello"); converter.Close(); converter write close both streams Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Simple type input BinaryReader reconstructs types from binary 23: Input and Output Simple type input BinaryReader reconstructs types from binary must be given a stream containing bytes Read methods read from backing stream and convert char, bool, string, short, int, long, float, double, etc. simple types converter bytes binary file data store FileStream data = new FileStream("Bytes.dat", FileMode.Open); BinaryReader converter = new BinaryReader(data); int i = converter.ReadInt32 (); double d = converter.ReadDouble(); string s = converter.ReadString(); converter.Close(); converter read close both streams Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Serialization Can save/restore state of object to stream 23: Input and Output Serialization Can save/restore state of object to stream called serialization save x 1 y 2 serialize Point x=1, y=2 ... restore deserialize x 1 y 2 Point x=1, y=2 ... Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Serializable attribute 23: Input and Output Serializable attribute Type author must explicitly allow serialization tag with Serializable attribute to allow otherwise get SerializationException allow points to be serialized [Serializable] class Point { int x; int y; ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Formatter BinaryFormatter used to serialize/deserialize object 23: Input and Output Formatter BinaryFormatter used to serialize/deserialize object in namespace System.Runtime.Serialization.Formatters.Binary public sealed class BinaryFormatter ... { public void Serialize(Stream destination, object o) ... } public object Deserialize(Stream source) save object to stream restore object from stream Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Save Use Serialize method to save object to stream void Write() { 23: Input and Output Save Use Serialize method to save object to stream void Write() { FileStream dest = new FileStream("MyData.dat", FileMode.Create); Point data = new Point(1, 2); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(dest, data); ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Restore Use Deserialize method to restore object from stream 23: Input and Output Restore Use Deserialize method to restore object from stream return type is object, typical to downcast void Read() { FileStream source = new FileStream("MyData.dat", FileMode.Open); BinaryFormatter formatter = new BinaryFormatter(); Point data = (Point)formatter.Deserialize(source); ... } Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Object graph Serialization preserves object graph 23: Input and Output Object graph Serialization preserves object graph all referenced objects are serialized graph rebuilt when deserialized x 1 y 2 center radius 3 c Both circle and center point would be serialized Programming C# © 2003 DevelopMentor, Inc. 12/1/2003
Summary IO facilities provided by .NET Framework class library 23: Input and Output Summary IO facilities provided by .NET Framework class library in System.IO namespace Can manipulate files and directories Can read/write file contents characters bytes Can convert simple types to/from binary format Serialization allows objects to be read/written to stream Programming C# © 2003 DevelopMentor, Inc. 12/1/2003