Input and Output Objectives Survey IO facilities in .NET - - PDF document
Input and Output Objectives Survey IO facilities in .NET - - PDF document
Input and Output Objectives Survey IO facilities in .NET Framework Class Library file and directory management text files binary files object serialization 2 IO Library Input/output library in System.IO namespace
Objectives
- Survey IO facilities in .NET Framework Class Library
– file and directory management – text files – binary files – object serialization
2
IO Library
3
- Input/output library in System.IO namespace
- Support provided for:
– file and directory management – text files – binary files – simple type conversion to/from binary
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
4
FileSystemInfo DirectoryInfo FileInfo
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
5
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 6
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 7
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
8
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); 9
Utility classes
- Three utility classes also work with files and directories
– Path – Directory – File
10
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; ... } 11
Application: parse path
- Path methods useful to parse path into constituent parts
12 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 C:\ .dll string path = @"C:\WINDOWS\system32\mscoree.dll"; Parse(path);
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 13
Application: examine drives
- Can examine all logical drives
– use Directory.GetLogicalDrives to get drives – use Directory.Exists to determine if disk in drive
string[] drives = Directory.GetLogicalDrives(); foreach (string s in drives) { if (Directory.Exists(s)) ... }
all drives disk in drive?
14
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 15
Choice of file / directory class
16
- 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
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
17
Character IO
- Classes provided to do character IO
– most methods defined in base classes – derived classes specialized for data location and operation
TextReader StreamReader StringReader TextWriter StreamWriter StringWriter
read from disk read from string write to disk write to StringBuilder
18
StreamWriter
automatically converted to string using ToString
- StreamWriter writes characters to text file
– open file with one of many constructors – write with overloaded Write / WriteLine methods – close
char, bool, string, short, int, long, float, double, etc.
text file 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();
- pen
write close
19
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
StreamReader sr = new StreamReader("Chores.txt"); string s; while ((s = sr.ReadLine()) != null) Console.WriteLine(s); sr.Close();
- pen
read close
20
Byte IO
- Classes provided to do byte IO
– most methods defined in base class
- Two possible data locations provided in System.IO
– disk – memory
21
Stream FileStream MemoryStream
read/write byte array read/write disk
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 22
FileStream
- FileStream supports read / write bytes to disk file
23 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();
- pen
write back up 2 bytes back up to beginning close
byte, byte[]
binary file
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
simple types bytes char, bool, string, short, int, long, float, double, etc.
converter binary file
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(); data store converter write close both streams 24
Simple type input
- BinaryReader reconstructs types from binary
– must be given a stream containing bytes – Read methods read from backing stream and convert
simple types bytes char, bool, string, short, int, long, float, double, etc.
converter binary file
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(); data store converter read close both streams 25
Serialization
- Can save/restore state of object to stream
– called serialization
26
x 1 y 2
serialize
save
Point x=1, y=2 ... x 1 y 2
deserialize
restore
Point x=1, y=2 ...
Serializable attribute
- Type author must explicitly allow serialization
– tag with Serializable attribute to allow – otherwise get SerializationException
[Serializable] class Point { int x; int y; ... }
allow points to be serialized
27
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
28
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); ... }
29
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); ... }
30
Object graph
- Serialization preserves object graph
– all referenced objects are serialized – graph rebuilt when deserialized
center radius 3 c x 1 y 2
Both circle and center point would be serialized
31
Summary
32
- 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