Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Files and Streams

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

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

Files and Streams

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

Access the files in a random fashion

MemoryStream

Access data stored in memory

StreamWriter
StreamReader

and Read and write textual information

StringReader
StringWriter

and Read and write textual Information from a string buffer

In addition to these concrete class types, System.IO defines a number of


enumerations, as well as a set of abstract classes (Stream, TextReader, TextWriter, and so
forth). The Directory(Info) and File(Info) Types System.IO provides four types that allow
you to manipulate individual files, as well as interact with a machines directory
structure. The first two types, Directory and File, expose creation, deletion, copying, and
moving operations using various static members. The closely related FileInfo and
DirectoryInfo types expose similar functionality as instance-level methods (and therefore
must be allocated with the new keyword).

Page 2

Files and Streams

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

Returns attributes associated with a file. Takes FileAttributes


enumeration values

CreationTime

Returns the time of creation of the file

Exists

Checks whether a supplied file is a directory or not

Extension

Returns the file extension

LastAccessTime Returns last accessed time of the file


FullName

Returns the full path of the file

LastWriteTime

Returns the time of last written activity to the file

Name

Returns the name of a given file

Page 3

Files and Streams


Delete()

Deletes a file. Be careful when using this method.

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()

Create a directory (or set of subdirectories), given a path


name

Delete()

Deletes a directory and all its contents

GetDirectories()

Returns an array of strings that represent all subdirectories


in the current directory

GetFiles()

Retrieves an array of FileInfo types that represent a set of


files in the given directory

MoveTo()

Moves a directory and its contents to a new path

Parent

Retrieves the parent directory of the specified path

Root

Gets the root portion of a path

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

Files and Streams


DirectoryInfo dir3 = new DirectoryInfo(@"C:\MyCode\Testing");
dir3.Create();
Once you have created a DirectoryInfo object, you can investigate the underlying
directory contents using any of the properties inherited from FileSystemInfo.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Directory(Info) *****\n");
ShowWindowsDirectoryInfo();
Console.ReadLine();
}
static void ShowWindowsDirectoryInfo()
{
// Dump directory information.
DirectoryInfo dir = new DirectoryInfo(@"C:\Windows");
Console.WriteLine("***** Directory Info *****");
Console.WriteLine("FullName: {0}", dir.FullName);
Console.WriteLine("Name: {0}", dir.Name);
Console.WriteLine("Parent: {0}", dir.Parent);
Console.WriteLine("Creation: {0}", dir.CreationTime);
Console.WriteLine("Attributes: {0}", dir.Attributes);
Console.WriteLine("Root: {0}", dir.Root);
Console.WriteLine("**************************\n");
}
}
Files with the DirectoryInfo Type
DirectoryInfo dir = new DirectoryInfo(@"C:\Windows\Web\Wallpaper");
// files with a *.txt extension.
FileInfo[] TextFiles = dir.GetFiles("*.txt");
foreach (FileInfo f in TextFiles)
{
Console.WriteLine("File name: {0}", f.Name);
Console.WriteLine("File size: {0}", f.Length);
Console.WriteLine("Creation: {0}", f.CreationTime);
Console.WriteLine("Attributes: {0}", f.Attributes);
}
Page 5

Files and Streams

Creating Subdirectories with the DirectoryInfo Type


You can programmatically extend a directory structure using the DirectoryInfo.
CreateSubdirectory() method. This method can create a single subdirectory, as well as
multiple nested subdirectories, in a single function call.
DirectoryInfo sourceDir = new DirectoryInfo("c:\\IIBC");
sourceDir.Create();
or
DirectoryInfo dir = new DirectoryInfo(".");
dir.CreateSubdirectory("MyFolder");
DirectoryInfo sourceDir = new DirectoryInfo("c:\\IIBC");
sourceDir.Create();
or
DirectoryInfo dir = new DirectoryInfo(".");
dir.CreateSubdirectory("MyFolder");
Directory Type
Get Files from root Directory
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Using: " + Directory.GetCurrentDirectory());
Console.WriteLine(Directory.Exists("c:\\"));
string[] aFiles = Directory.GetFiles("c:\\");
foreach (string s in aFiles)
Console.WriteLine(s);
}
}
// List all drives on current computer.
string[] drives = Directory.GetLogicalDrives();
Console.WriteLine("Here are your drives:");
foreach (string s in drives)
Console.WriteLine("--> {0} ", s);
// Delete what was created.
Console.WriteLine("Press Enter to delete directories");
Console.ReadLine();
Page 6

Files and Streams


Directory.Delete(string.Format(@"{0}\MyFolder",
Environment.CurrentDirectory));

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)

FileMode Enumeration values.


Values

Purpose/Use

Append

Opens the file and adds data. This should be used with the FileAccess
Write Enumeration value.

Create

Creates a new file. Overwrites any existing file.

CreateNew

Creates a new file. If the file already exists, IOException is thrown.

Open

Opens an existing file

OpenOrCreate Opens a new file. If there is no file, it creates a new file.


Page 7

Files and Streams


Truncate

Truncates an existing file

FileAccess Enumeration values


Values

Purpose/Use

Read

Data can be read (retrieved) from the file

ReadWrite

Data can be added to and retrieved from the file

Write

Data can be added to the file

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())

FileInfo.CreateText() and FileInfo.AppendText()


FileInfo f6 = new FileInfo(@"C:\Test5.txt");
using(StreamWriter swriter = f6.CreateText())
FileInfo f7 = new FileInfo(@"C:\FinalTest.txt");
using(StreamWriter swriterAppend = f7.AppendText())

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

Files and Streams


// Obtain FileStream object via File.Create().
using(FileStream fs = File.Create(@"C:\Test.dat"))
{
}
// Obtain FileStream object via File.Open().
using(FileStream fs2 = File.Open(@"C:\Test2.dat",
FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None))
{
}
// Get a FileStream object with read-only permissions.
using(FileStream readOnlyStream = File.OpenRead(@"Test3.dat"))
{
}
// Get a FileStream object with write-only permissions.
using(FileStream writeOnlyStream = File.OpenWrite(@"Test4.dat"))
{
}
// Get a StreamReader object.
using(StreamReader sreader = File.OpenText(@"C:\boot.ini"))
{
}
// Get some StreamWriters.
using(StreamWriter swriter = File.CreateText(@"C:\Test3.txt"))
{
}
using(StreamWriter
swriterAppend
File.AppendText(@"C:\FinalTest.txt"))
{
}
}

Example:
class Program
{
Page 9

Files and Streams


static void Main(string[] args)
{
StreamWriter writer = new StreamWriter(@"c:\myfile.txt");
for (int i = 0; i < 3; i++)
{
writer.Write(i.ToString());
}
foreach (string line in File.ReadAllLines(@"c:\myfile.txt"))
{
Console.WriteLine(line);
}
}
}
class MainClass
{
public static void Main(string[] args)
{
FileInfo file = new FileInfo("c:\\test.txt");
Console.WriteLine("Checking file: " + file.Name);
Console.WriteLine("File exists: " + file.Exists.ToString());
if (file.Exists)
{
Console.Write("File created: ");
Console.WriteLine(file.CreationTime.ToString());
Console.Write("File last updated: ");
Console.WriteLine(file.LastWriteTime.ToString());
Console.Write("File last accessed: ");
Console.WriteLine(file.LastAccessTime.ToString());
Console.Write("File size (bytes): ");
Console.WriteLine(file.Length.ToString());
Console.Write("File attribute list: ");
Console.WriteLine(file.Attributes.ToString());
}
}
Page 10

Files and Streams


}

The Abstract Stream Class


In the world of I/O manipulation, a stream represents a chunk of data flowing
between a source and a destination. Streams provide a common way to interact with a
sequence of bytes, regardless of what kind of device (file, network connection, printer,
etc.) is storing or displaying the bytes in question. The abstract System.IO.Stream class
defines a number of members that provide support for synchronous and asynchronous
interactions with the storage medium.
Working with FileStreams
The FileStream class provides an implementation for the abstract Stream
members in a manner appropriate for file-based streaming. It is a fairly primitive stream;
it can read or write only a single byte or an array of bytes.
FileStream fin=new FileStream("test.dat", FileMode.Open);
// Write the alphabet.
for(int i=0; i < 26; i++)
f.WriteByte((byte)('A'+i));
f.Seek(0, SeekOrigin.Begin); // seek to first byte
ch = (char) f.ReadByte();
Console.WriteLine("First value is " + ch);
f.Seek(1, SeekOrigin.Begin); // seek to second byte
ch = (char) f.ReadByte();
Console.WriteLine("Second value is " + ch);
f.Seek(4, SeekOrigin.Begin); // seek to 5th byte
ch = (char) f.ReadByte();
Console.WriteLine("Fifth value is " + ch);
Console.WriteLine();

static void Main(string[] args)


{
FileStream MyFileStream1 = new FileStream(@"c:\Testing.txt", FileMo
de.Create);
int NumberOfBytesToWrite = 256;
byte[] MyWriteByteArray = new Byte[NumberOfBytesToWrite];
Page 11

Files and Streams

for (int i = 0; i < 256; i++)


{
MyWriteByteArray[i] = (byte)i;
i++;
}
MyFileStream1.Write(MyWriteByteArray, 0, NumberOfBytesToWrite);
MyFileStream1.Close();
}
StreamWriters and StreamReaders
StreamReader derives from an abstract type named TextReader, as does the
related StringReader type (discussed later in this chapter). The TextReader base class
provides a very limited set of functionality to each of these descendents, specifically the
ability to read and peek into a character stream. The StreamWriter type (as well as
StringWriter, also examined later in this chapter) derives from an abstract base class
named TextWriter. This class defines members that allow derived types to write textual
data to a given character stream.

Writing to a Text File


Console.WriteLine("***** Fun with StreamWriter / StreamReader
*****\n");
// Get a StreamWriter and write string data.
using(StreamWriter writer = File.CreateText("reminders.txt"))
{
writer.WriteLine("Don't forget Mother's Day this year...");
writer.WriteLine("Don't forget Father's Day this year...");
writer.WriteLine("Don't forget these numbers:");
for(int i = 0; i < 10; i++)
writer.Write(i + " ");
// Insert a new line.
writer.Write(writer.NewLine);
}
Page 12

Files and Streams

Reading from a Text File


using(StreamReader sr = File.OpenText("reminders.txt"))
{
string input = null;
while ((input = sr.ReadLine()) != null)
{
Console.WriteLine (input);
}
}
BufferedStream
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. A
buffer can be used for either reading or writing, but never both simultaneously. The Read
and Write methods of BufferedStream automatically maintain the buffer.
Reading large file performance
using
using
using
using
using

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

Files and Streams


String line;
reader = new StreamReader(bstream);
while ((line = reader.ReadLine()) != null)
{
totalRows++;
}
stream.Close();
}
}
}

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

Files and Streams


Write a Program to watch for any changes in the directory which includes files
and subdirectories.
Write a program to encrypt and decrypt the contents of a text file.
Write the Program to save the output of a program onto a text file.

Page 15

You might also like