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
• Support provided for:
– file and directory management – text files – binary files – simple type conversion to/from binary
3
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
4
FileSystemInfo
• Files and directories have some operations in common
– provided in base class FileSystemInfo
name
public abstract class FileSystemInfo ... {
characteristics
public abstract string Name { get; } public string FullName { get; } public string Extension { get; }
delete
{ get; } public abstract bool Exists public DateTime CreationTime { get; set; } public DateTime LastAccessTime { get; set; } public DateTime LastWriteTime { get; set; } { get; set; } public FileAttributes Attributes
public void 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) ... constructor
navigation public DirectoryInfo Parent { get; } { get; } public DirectoryInfo Root
manipulation
() ... public void Create (string destDirName) ... public void MoveTo (bool recursive ) ... public void Delete public DirectoryInfo CreateSubdirectory(string path ) ...
contents
() ... public FileInfo [] GetFiles public DirectoryInfo [] GetDirectories () ... public FileSystemInfo[] GetFileSystemInfos() ... ...
}
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) ... constructor
public long Length { get; } length
location public string DirectoryName { get; } public DirectoryInfo Directory { get; }
manipulation
public FileInfo CopyTo(string destFileName) ... public FileInfo CopyTo(string destFileName, bool overwrite) ... public void MoveTo(string destFileName) ... ...
}
7
Application: List contents
• Can examine contents of a directory
void List(string path) {
DirectoryInfo directory = new DirectoryInfo(path);
contents
FileInfo [] files = directory.GetFiles (); DirectoryInfo[] directories = directory.GetDirectories();
files
foreach (FileInfo f in files) Console.WriteLine(f.Name);
directories
foreach (DirectoryInfo d in directories)
Console.WriteLine(d.Name);
}
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)) search with pattern results.Add(f.FullName);
foreach (DirectoryInfo d in root.GetDirectories())
Find(filename, d, results); 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
public void Parse(string path) { C:\WINDOWS\system32 string a = Path.GetDirectoryName (path);
mscoree.dll string b = Path.GetFileName (path);
mscoree string c = Path.GetFileNameWithoutExtension(path);
.dll string d = Path.GetExtension (path);
C:\ string e = Path.GetPathRoot (path);
...
}
string path = @"C:\WINDOWS\system32\mscoree.dll";
Parse(path);
12
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() all drives on system
current directory public static string GetCurrentDirectory() public static void SetCurrentDirectory(string path)
similar methods in DirectoryInfo
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) ...
}
13
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) {
disk in drive?
if (Directory.Exists(s))
...
}
14
File
• File has static methods to manipulate files
– all have analogues in FileInfo
public sealed class File {
similar methods in FileInfo
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) ... ...
}
15
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
16
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
TextWriter
StreamReader
StringReader
StreamWriter
StringWriter
write to disk
read from disk
write to StringBuilder
read from string
18
StreamWriter
• StreamWriter writes characters to text file – open file with one of many constructors – write with overloaded Write / WriteLine methods – close
text file
automatically converted to string using ToString
open
char, bool, string, short, int, long, float, double, etc.
StreamWriter sw = new StreamWriter("Chores.txt"); int n = 3;
write
sw.WriteLine("Go to pet store"); sw.Write("Feed all "); sw.Write(n); sw.WriteLine(" cats");
sw.Close();
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
text file
open
can read only char or string char, string
StreamReader sr = new StreamReader("Chores.txt"); string s;
read
while ((s = sr.ReadLine()) != null)
Console.WriteLine(s);
close
sr.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
Stream
FileStream
MemoryStream
read/write disk
read/write byte array
21
Stream methods
• Stream offers extensive functionality
– read / write bytes – random access – asynchronous read / write
public abstract class Stream ... {
read/write
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);
(long offset, SeekOrigin origin);
public abstract long Seek public abstract long Position { get; set; } random access
asynch
public virtual IAsyncResult BeginRead (...) ... (...) ... public virtual int EndRead public virtual IAsyncResult BeginWrite(...) ... public virtual void EndWrite (...) ... ...
}
22
FileStream
• FileStream supports read / write bytes to disk file
open
FileStream f = new FileStream
(
"Bytes.dat", FileMode.Create, FileAccess.ReadWrite
binary file
);
write
byte, byte[]
back up 2 bytes
f.WriteByte((byte)10); f.WriteByte((byte)20); f.WriteByte((byte)30); f.WriteByte((byte)90); f.WriteByte((byte)50);
back up to beginning
f.Seek(-2, SeekOrigin.Current); f.WriteByte((byte)40);
f.Seek(0, SeekOrigin.Begin); int b = f.ReadByte();
close
f.Close();
23
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
converter
binary file
simple types bytes
char, bool, string, short, int, long, float, double, etc.
data store FileStream data = new FileStream("Bytes.dat", FileMode.Create);
converter BinaryWriter converter = new BinaryWriter(data);
write
converter.Write(17); converter.Write(3.14); converter.Write("hello");
converter.Close(); 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
converter
binary file
simple types bytes
char, bool, string, short, int, long, float, double, etc.
data store FileStream data = new FileStream("Bytes.dat", FileMode.Open);
converter BinaryReader converter = new BinaryReader(data);
read
int i = converter.ReadInt32 (); double d = converter.ReadDouble(); string s = converter.ReadString();
converter.Close(); close both streams
25
Serialization
• Can save/restore state of object to stream
– called serialization
Point x=1, y=2 ...
save serialize
x 1 y 2
Point x=1, y=2 ...
restore deserialize
x 1 y 2
26
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; ...
}
27
Formatter
• BinaryFormatter used to serialize/deserialize object
– in namespace
System.Runtime.Serialization.Formatters.Binary
public sealed class BinaryFormatter ... {
save object to stream
public void Serialize(Stream destination, object o) {
...
}
restore object from stream
public object Deserialize(Stream source) {
...
} ...
}
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
x 1 y 2
c
center radius 3
Both circle and center point would be serialized
31
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
32

