Files and Streams
Files and Streams
FILES AND
STREAMS
Objectives
This chapter provides complete knowledge on
How to work with System.IO namespace
How to work with Files, directories and Drives
How to work with Streams
Page 1
Introduction
System.IO Namespace
In the framework of .NET, the System.IO namespace is the region of the base
class libraries devoted to file-based (and memory-based) input and output (I/O) services.
Like any namespace, System.IO defines a set of classes, interfaces, enumerations,
structures, and delegates. Many of the types within the System.IO namespace focus on
the programmatic manipulation of physical directories and files. However, additional
types provide support to read data from and write data to string buffers as well as raw
memory locations. The below table elaborates the main classes under this namespace.
Class
Purpose/Use
Binary Reader and Writer Read and write primitive data types
Directory,
DirectoryInfo,
FileInfo
File, Create, delete, and move files and directories. Get specific
and information about the files by making use of the properties
defined in these classes.
FileStream
MemoryStream
StreamWriter
StreamReader
StringReader
StringWriter
Page 2
FileInfo and DirectoryInfo are better choices for obtaining full details of a file or
directory as their members tend to return strongly typed objects. In contrast, the Directory
and File class members tend to return simple string values rather than strongly typed
objects.
The Abstract FileSystemInfo Base Class
The DirectoryInfo and FileInfo types receive many behaviors from the abstract
FileSystemInfo base class. For the most part, the members of the FileSystemInfo class
are used to discover general characteristics (such as time of creation, various attributes,
and so forth) about a given file or directory.
Below table elaborates its properties and methods.
Properties
Purpose/Use
Attributes
CreationTime
Exists
Extension
LastWriteTime
Name
Page 3
DirectoryInfo
The first creatable I/O-centric type you will examine is the DirectoryInfo class. This class
contains a set of members used for creating, moving, deleting, and enumerating over
directories and subdirectories. In addition to the functionality provided by its base class
(FileSystemInfo), DirectoryInfo offers the key members in below table.
Member
Use
Create(),
CreateSubdirectory()
Delete()
GetDirectories()
GetFiles()
MoveTo()
Parent
Root
You begin working with the DirectoryInfo type by specifying a particular directory path
as a constructor parameter. If you want to obtain access to the current working directory
(i.e., the directory of the executing application), use the "." notation. Here are some
examples:
// Bind to the current working directory.
DirectoryInfo dir1 = new DirectoryInfo(".");
// Bind to C:\Windows, using a verbatim string.
DirectoryInfo dir2 = new DirectoryInfo(@"C:\Windows");
In the second example, you are making the assumption that the path passed into the
constructor (C:\Windows) already exists on the physical machine. However, if you
attempt to interact with a nonexistent directory,
a System.IO.DirectoryNotFoundException is thrown. Thus, if you specify a
directory that is not yet created, you will need to call the Create() method before
proceeding:
// Bind to a nonexistent directory, then create it.
Page 4
FileInfo
FileInfo class allows you to obtain details regarding existing files on your hard
drive (time created, size, file attributes, and so forth) and aids in the creation, copying,
moving, and destruction of files.
FileInfo.Create() Method
FileInfo f = new FileInfo(@"C:\IIBC.txt");
FileStream fs = f.Create();
Be aware that the FileStream object returned by FileInfo.Create() grants full read/write
access to all users.
FileInfo.Open() Method
You can use the FileInfo.Open() method to open existing files as well as create
new files with far more precision than FileInfo.Create(), given that Open() typically takes
several parameters to qualify the overall structure of the file you are manipulating.
FileInfo f2 = new FileInfo(@"C:\Test2.dat");
FileStream
fs2
=
f2.Open(FileMode.OpenOrCreate,FileAccess.ReadWrite,
FileShare.None)
Purpose/Use
Append
Opens the file and adds data. This should be used with the FileAccess
Write Enumeration value.
Create
CreateNew
Open
Purpose/Use
Read
ReadWrite
Write
FileInfo.OpenRead()
FileInfo f3 = new FileInfo(@"C:\Test3.dat");
using(FileStream readOnlyStream = f3.OpenRead())
FileInfo.OpenWrite()
FileInfo f4 = new FileInfo(@"C:\Test4.dat");
using(FileStream writeOnlyStream = f4.OpenWrite())
FileInfo.OpenText()
FileInfo f5 = new FileInfo(@"C:\boot.ini");
using(StreamReader sreader = f5.OpenText())
File Type
The File type provides functionality almost identical to that of the FileInfo type, using a
number of static members. Like FileInfo, File supplies AppendText(), Create(),
CreateText(), Open(), OpenRead(), OpenWrite(), and OpenText()methods.
static void Main(string[] args)
{
Page 8
Example:
class Program
{
Page 9
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.IO;
namespace readfilebufferedclass
{
class Program
{
static void Main(string[] args)
{
int totalRows = 0;
Stream stream = new FileStream("d:/test.txt");
BufferedStream bstream = new BufferedStream(stream);
char[] delimiters = { '\t' };
StreamReader reader;
Page 13
Points to Remember
System.IO namespace is the region of the base class libraries devoted to filebased (and memory-based) input and output (I/O) services.
Many of the types within the System.IO namespace focus on the programmatic
manipulation of physical directories and files.
You can programmatically extend a directory structure using the DirectoryInfo.
CreateSubdirectory() method.
FileInfo class allows you to obtain details regarding existing files on your hard
drive and aids in the creation, copying, moving, and destruction of files.
The abstract System.IO.Stream class defines a number of members that provide
support for synchronous and asynchronous interactions with the storage medium.
A buffer is a block of bytes in memory used to cache data, thereby reducing the
number of calls to the operating system.
Buffers improve read and write performance.
Check YourSelf
Exercise
Write a Program to copy files from one directory to other directory.
Write a Program to copy the whole directory.
Page 14
Page 15