input and output objectives
play

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


  1. Input and Output

  2. Objectives • Survey IO facilities in .NET Framework Class Library – file and directory management – text files – binary files – object serialization 2

  3. 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

  4. 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

  5. FileSystemInfo • Files and directories have some operations in common – provided in base class FileSystemInfo public abstract class FileSystemInfo ... { public abstract string Name { get; } name public string FullName { get; } public string Extension { get; } public abstract bool Exists { get; } public DateTime CreationTime { get; set; } characteristics public DateTime LastAccessTime { get; set; } public DateTime LastWriteTime { get; set; } public FileAttributes Attributes { get; set; } delete public void Delete() ... ... } 5

  6. DirectoryInfo • DirectoryInfo represents a directory – methods provided to examine and manipulate – inherits common operations from FileSystemInfo public sealed class DirectoryInfo : FileSystemInfo { constructor public DirectoryInfo(string path) ... public DirectoryInfo Parent { get; } navigation public DirectoryInfo Root { get; } public void Create () ... public void MoveTo (string destDirName) ... manipulation public void Delete (bool recursive ) ... public DirectoryInfo CreateSubdirectory(string path ) ... public FileInfo [] GetFiles () ... contents public DirectoryInfo [] GetDirectories () ... public FileSystemInfo[] GetFileSystemInfos() ... ... } 6

  7. 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 public string DirectoryName { get; } location public DirectoryInfo Directory { get; } public FileInfo CopyTo(string destFileName) ... public FileInfo CopyTo(string destFileName, bool overwrite) ... manipulation public void MoveTo(string destFileName) ... ... } 7

  8. Application: List contents • Can examine contents of a directory void List(string path) { DirectoryInfo directory = new DirectoryInfo(path); FileInfo [] files = directory.GetFiles (); contents DirectoryInfo[] directories = directory.GetDirectories(); foreach (FileInfo f in files) files Console.WriteLine(f.Name); directories foreach (DirectoryInfo d in directories) Console.WriteLine(d.Name); } 8

  9. Application: Find file • Can search file system to find specified files void Find(string filename, DirectoryInfo root, ArrayList results) { search with foreach (FileInfo f in root.GetFiles(filename)) pattern results.Add(f.FullName); recursive call for each foreach (DirectoryInfo d in root.GetDirectories()) Find(filename, d, results); 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

  10. Utility classes • Three utility classes also work with files and directories – Path – Directory – File 10

  11. 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

  12. 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

  13. 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 public static string GetCurrentDirectory() current directory public static void SetCurrentDirectory(string path) public static bool Exists (string path) ... public static string[] GetFiles (string path) ... similar methods in public static string[] GetDirectories(string path) ... DirectoryInfo public static void Delete (string path) public static void Move(string source, string dest) ... } 13

  14. 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(); all drives foreach (string s in drives) { if (Directory.Exists(s)) disk in drive? ... } 14

  15. File • File has static methods to manipulate files – all have analogues in FileInfo public sealed class File { public static bool Exists(string path) ... similar methods public static void Delete(string path) ... in FileInfo public static void Copy (string source, string dest) ... public static void Move (string source, string dest) ... ... } 15

  16. 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

  17. 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

  18. 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 StringBuilder read from string write to disk read from disk 18

  19. 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 char , bool , string , using ToString short , int , long , text file float , double , etc. open StreamWriter sw = new StreamWriter("Chores.txt"); int n = 3; sw.WriteLine("Go to pet store"); sw.Write("Feed all "); write sw.Write(n); sw.WriteLine(" cats"); sw.Close(); close 19

  20. 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"); open string s; while ((s = sr.ReadLine()) != null) read Console.WriteLine(s); sr.Close(); close 20

  21. 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

  22. 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) ... read/write 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); random public abstract long Position { get; set; } access public virtual IAsyncResult BeginRead (...) ... public virtual int EndRead (...) ... asynch public virtual IAsyncResult BeginWrite(...) ... public virtual void EndWrite (...) ... ... } 22

  23. FileStream • FileStream supports read / write bytes to disk file open FileStream f = new FileStream ( "Bytes.dat", FileMode.Create, FileAccess.ReadWrite ); byte , binary file byte[] f.WriteByte((byte)10); f.WriteByte((byte)20); write f.WriteByte((byte)30); f.WriteByte((byte)90); f.WriteByte((byte)50); back up 2 bytes f.Seek(-2, SeekOrigin.Current); f.WriteByte((byte)40); back up to beginning f.Seek(0, SeekOrigin.Begin); int b = f.ReadByte(); close f.Close(); 23

Recommend


More recommend