Exploring the System.IO Namespace


The System.IO namespace is the region of the base class libraries devoted to file-base (and memory-based) input and output (I/O) services. Like any namespace, System.IO defines a set of class,interfaces,and enumerations, structures and delegates, most of which you can find in mscorlib.dll. In addition to types contained within mscorlib.dll, the System.dll assembly defines additional members of the System.IO namespace.

Nonabstract I/O Class Type:

  1. BinaryReader / BinaryWriter : Those classes allow you to store and retrieve primitive data types(integers,Booleans,strings and whatnot) as a binary value.
  2. BufferedStream : This class provides temporary storage for a stream of bytes that you can commit to storage later.
  3. Directory and DirectoryInfo : You use these classes to manipulate a machine's directory structure. The Directory type exposes functionality using "static members", while the DirectoryInfo type exposes similar functionality from a valid "object reference".
  4. DriveInfo : This class provides detailed information regarding the drives that a given machine uses.
  5. File/FileInfo : You use these classes to manipulate a machine's set of files. The file type exposes functionality using static members, while the FileInfo type exposes similar functionality from a valid object reference.
  6. FileStream : This class allows you to monitor the modification of external files in a specified directory.
  7. MemoryStream : This class provides random access to streamed data stored in memory rather than in a physical file.
  8. Path : This class performs operations on System.String types that contain file or directory path information on in a platform- neutral manner.
  9. StreamWriter / StreamReader : You use these classes to store (and retrieve) textual information to (or from) a file. These types do not support random file access.
  10. StringWriter / StringReader : Like StreamWriter/StreamReader classes, these classes also work with textual information. However, the underlying storage is a string buffer rather than a physical file.

The Directory(Info) and File(Info) Types

The Directory and File classes directly extend System.Object, while DirectoryInfo and FileInfo derive from the abstract FileSystemInfo type.

The Abstract FileSystemInfo Base Class

The DirectoryInfo and FileInfo types receive many behaviors from the abstract FileSystemInfo base class.

Properties

  1. Attributes : Gets or sets the attributes associated with the current file that are represented by the FileAttributes enumeration (e.g. is the file or directory read-only, encrypted, hidden, or compressed?)
  2. CreatingTime : Gets or sets the time of creation for the current file or directory
  3. LastAccessTime : Gets or sets the time the current file or directory was/last accessed.
  4. LastWriteTime : Gets or sets the time when the current file or directory was last written to.
  5. Name : Obtains the name of the current file or directory.
  6. FullName : Gets the full path of the directory or file.
  7. Extension : Retrieves a file's extension.
  8. Exists : Determines whether a given file or directory exists.

Method

  1. Delete() : This is implemented by derived types to delete a given file or directory from the hard drive.
  2. Refresh() : Prior to obtaining attribute information to ensure that the statistics regarding the current file (or directory) are not outdated.

Working with the DirectoryInfo Type

This class contains a set of members used for creating, moving, deleting and enumerating over directories and subdirectories.

Key Members

  1. Create() : Creates directory (or set of subdirectories) when a given path name CreateSubDirectory().
  2. Delete() : Deletes a directory and all its contents.
  3. GetDirectories() : Returns an array of DirectoryInfo objects that represent all subdirectories in the current directory.
  4. GetFiles() : Retrieves an array of FileInfo objects that represent a set of files in the given directory.
  5. MoveTo() : Moves a directory and its contents to a new path.
  6. Parent : Retrieves the parent directory of this directory.
  7. Root : Gets the root partion of a path.

DirectoryInfo dir1 = new DirectoryInfo("."); // "." = current directory
DirectoryInfo dir2 = new DirectoryInfo(@"C:\Windows"); // Bind to C:\Windows
DirectoryInfo dir3 = new DirectoryInfo(@"C:\MyCode\Testing");
dir3.Create();
// If you attempt to inteact with a nonexistent directory a System.IO.DirectoryNotFoundException is thrown.

If you are developing .NET applications for different platforms, you should use the Path.VolumeSeparatorChar and Path.DirectorySeparatorChar.

DirectoryInfo dir4 = new DirectoryInfo($@"C{Path.VolumeSeparatorChar}{Path.DirectorySeparatorChar}MyCode{Path.DirectorySeparatorChar}Testing");
Console.WriteLine(dir4.FullName);
Console.WriteLine(dir4.Name);
Console.WriteLine(dir4.Parent);
Console.WriteLine(dir4.CreateSubdirectory);
Console.WriteLine(dir4.Attributes);
Console.WriteLine(dir4.Root);

Enumerating Files with the DirectoryInfo Type

Let's take all *.jpg files in the C:\Wallpaper.

DirectoryInfo dir = new DirectoryInfo(@$"C{Path.VolumeSeparatorChar}{Path.DirectorySeparatorChar}Wallpaper");
FileInfo[] imageFiles = dir.GetFiles("*.jpg", SearchOption.AllDirectories);
Console.WriteLine(imageFiles.Length);
foreach (FileInfo f in imageFiles)
 {
     Console.WriteLine(f.Name+" "+f.Length+" "+f.CreationTime+" "+f.Attributes);
 }

Creating Subdirectories with the DirectoryInfo Type

DirectoryInfo dir = new DirectoryInfo(".");
dir.CreateSubdirectory("MyFolder"); // Create \MyFolder
dir.CreateSubdirectory($@"MyFolder{Path.DirectorySeparatorChar}Data"); // Create \MyFolder\Data

You can capture the return value:

DirectoryInfo myDataFolder =  dir.CreateSubdirectory($@"MyFolder{Path.DirectorySeparatorChar}Data"); // Create \MyFolder\Data

Working with the Directory Type

That the members of Directory typically return string data rather than strongly typed FileInfo/DirectoryInfo objects.

// List all drives on current computer
string[] drives = Directory.GetLogicalDrives();
foreach(string drive in drives)
 {
     Console.WriteLine(drive);
 }
Directory.Delete("MyFolder");
// The second param specifies whether you wish to destroy any subdirectories.
Directory.Delete("MyFolder2", true);

Working with the DriveInfo Class Type

DriveInfo.GetDrives() method allows you to discover the names of a machine's drives.

DriveInfo[] myDrives = DriveInfo.GetDrives();
foreach(DriveInfo d in myDrives)
 {
     Console.WriteLine(d.Name);
     Console.WriteLine(d.DriveType);
     if (d.IsReady)
     {
         Console.WriteLine(d.TotalFreeSpace);
         Console.WriteLine(d.DriveFormat);
         Console.WriteLine(d.VolumeLabel);
     }
 }

Working with the FileInfo Class

Member

  1. AppendText() : Creates a StreamWriter object that appends text to a file.
  2. CopyTo() : Copies an existing file to a new file.
  3. Create() : Creates a new file and returns a FileStream object to interact with the newly created file.
  4. CreateText() : Creates a StreamWriter object that writes a new text file.
  5. Delete() : Deletes the file to which a FileInfo instance is bound.
  6. Directory : Gets an instance of the parent directory.
  7. DirectoryName : Gets the full path to the parent directory.
  8. Length : Gets the size of the current file.
  9. MoveTo() : Moves a specified file to a new location, providing the option to specify a new filename.
  10. Name : Gets the name of the file.
  11. Open() : Opens a file with various read/write and sharing privileges.
  12. OpenRead() : Creates a read-only FileStream object.
  13. OpenText() : Creates a StreamReader object that reads from an existing text file.
  14. OpenWrite() : Creates a write-only FileStream object.

The FileInfo.Create() Method

var fileName = $@"C{Path.VolumeSeparatorChar}{Path.DirectorySeparatorChar}temp{Path.DirectorySeparatorChar}Test.dat";
FileInfo f = new FileInfo(fileName);
FileStream fs = f.Create();
// Use the object
fs.Close();
FileInfo f1 = new FileInfo(fileName);
using(FileStream fs1 = f1.Create())
 {
     // Use
 }
f1.Delete();

The FileInfo.Open() Method

FileInfo f2 = new FileInfo(fileName);
using(FileStream fs2 = f2.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
 {
     // Use
 }
f2.Delete();
 
public enum FileMode
 {
     CreateNew,
     Create,
     Open,
     OpenOrCreate,
     Truncate,
     Append
 }

  1. CreateNew : Informs the OS to make a new file. If it already exists, an IOException is thrown.
  2. Create : Informs the OS to make a new file. If it already exists, it will be overwritten.
  3. Open : Opens an existing file. If the file does not exist, a FileNotFoundException is thrown.
  4. OpenOrCreate : Opens the file if it exists; otherwise, a new file is created.
  5. Truncate : Opens an existing file and truncates the file to 0 bytes in size.
  6. Append : Opens a file, moves to the end of the file, and begins write operations (you can use this flag only with a write-only stream). If the file does not exist, a new file is created.

public enum FileAccess
 {
     Read,
     Write,
     ReadWrite
 }
public enum FileShare
 {
     None,
     Read,
     Write,
     ReadWrite,
     Delete,
     Inheritable
 }

The FileInfo.OpenRead() and FileInfo.OpenWrite() Methods

var fileName = $@"C{Path.VolumeSeparatorChar}{Path.DirectorySeparatorChar}temp{Path.DirectorySeparatorChar}Test.dat";
// Get a FileStream object with read-only permissions.
FileInfo f3 = new FileInfo(fileName);
f3.Create().Close();
using(FileStream readOnlyStream = f3.OpenRead())
 {
     // Use the FileStream object...
 }
f3.Delete();
// Now get a FileStream object with write-only permissions
FileInfo f4 = new FileInfo(fileName);
using(FileStream writeOnlyStream = f4.OpenWrite())
 {
     // Use the FileStream object...
 }
f4.Delete();

The FileInfo.OpenText() Method

var fileName = $@"C{Path.VolumeSeparatorChar}{Path.DirectorySeparatorChar}temp{Path.DirectorySeparatorChar}Test.dat";
// Get a StreamReader object. If not on a Windows machine, change the file name accordingly.
FileInfo f5 = new FileInfo(fileName);
// File must exist before using OpenText
f5.Create().Close();
using(StreamReader sReader = f5.OpenText())
 {
     // Use the StreamReader object.
 }
f5.Delete();

The FileInfo.CreateText() and FileInfo.AppendText() Methods

var fileName = $@"C{Path.VolumeSeparatorChar}{Path.DirectorySeparatorChar}temp{Path.DirectorySeparatorChar}Test.dat";
         
FileInfo f6 = new FileInfo(fileName);
using(StreamWriter sWriter = f6.CreateText())
 {
     // Use the StreamWriter object...
 }
f6.Delete();
FileInfo f7 = new FileInfo(fileName);
using(StreamWriter sWriterAppend = f7.AppendText())
 {
     // Use them StreamWriter object...
 }
f7.Delete();