The .Net framework provides a few basic classes for creating, reading and writing to files on the secondary storage and for retrieving file system information. They are located in the System.IO namespace and used both in desktop applications and the web applications.

Introduction

The .Net framework provides a few basic classes for creating, reading and writing to files on the secondary storage and for retrieving file system information. They are located in the System.IO namespace and used both in desktop applications and the web applications. We can categorise our file handling jobs in two parts –

1.     Implementing File Input and Output Operations – this involves reading and writing from and to a file saved on the disk. When a file is opened, the data from the file is stored into a sequence of bytes called Stream. Your program uses this stream to retrieve or store data. C# provides a FileStream class and as well as StreamReader and StreamWriter classes to read from and write to a byte stream. Again, data could be binary data, instead of sequence of bytes. For that we have BinaryReader and BinaryWriter classes.

2.     Working with the File System – this involves accessing the files and directory present in your system and performing typical file system operations such as copying files and creating directories. System.IO namespace provides classes working with the file system of a machine as seen by the server. These classes could be categorised into two parts:

 

·        Directory and File classes: these classes provides the static methods that allow retrieving information about any files and directories

·        DirectoryInfo and FileInfo classes: these classes use similar instance methods and properties.

Both group of classes provide similar methods and properties, the difference being –  you need to have a DirectoryInfo or FileInfo object to use the methods of second group of classes, whereas the static methods of first group of classes are always available.

Implementing the File Input and Output Operations

The System.IO namespace includes various classes, which are used to perform operations, like file creation, file deletion, and the read-write operations to files. Before moving into details, let us have a look at the commonly used class of the System.IO namespace.

Class Name

Description

FileStream

Is used to read from and write to any location within a file

BinaryReader

Is used to read primitive data types from a binary stream

BinaryWriter

Is used to write primitive data types in binary format

StreamReader

Is used to read characters from a byte stream

StreamWriter

Is used to write characters to a stream

StringReader

Is used to read from a string buffer

StringWriter

Is used to write into a string buffer

DirectoryInfo

Is used to perform operations on directories

FileInfo

Is used to perform operations on files

 

The FileStream Class

You need to create a FileStream object to open an existing file or create a new file. The syntax for this is as follows:

FileStream <object name> = new FileStream(<File Name>, <FileMode>, <File Access>, <File Share>);

For example:

FileStream fs = new FileStream(“myfile.txt”, FileMode.Open, FileAccess.Read, FileShare.Read);

The FileMode Enumerator

This enumerator defines various methods for opening files. Parameters to it checks whether a file is overwritten, created or opened. The members of the FileMode enumerator are:

Parameter

Description

Append

Opens the file if it exists and places the cursor and the end of the file, or creates a new file.

Create

Creates a new file.

CreateNew

Specifies to the operating system that a new file should be created.

Open

Opens an existing file

OpenOrCreate

Specifies to the operating system that it should open a file if it exists; else, it should create a new file

Truncate

Opens an existing file and truncates it to zero byte.

 

The FileAccess Enumerator

Unless specified, the file is opened for both reading and writing. This enumerator has members: Read, Write, and ReadWrite.

The FileShare Enumerator

This enumerator contains constants for controlling the sharing of a file by other FileStream objects; it typically sets whether two different applications can simultaneously read from same file. The members are:

Parameter

Description

Inheritable

Allows a file handle to pass inheritance to the child processes

None

Declines sharing of a current file

Read

Allows opening of a file for reading

ReadWrite

Allows opening of a file for reading and writing

Write

Allows opening of a file for writing

 

The StreamReader and StreamWriter        

The abstract Stream class is used to read from and to write data in the text files by keeping the data into a stream.  The StreamReader and StreamWriter classes inherit from two more abstract classes TextReader and TextWriter classes to accomplish the process of reading and writing.

The following code demonstrates copying text from one file to another:

using System;

using System.IO;

class FileCopy

{

public void copyfile()

{

      FileStream f1 = new FileStream("source.txt", FileMode.Open, FileAccess.Read);

      FileStream f2 = new FileStream("target.txt", FileMode.Append, FileAccess.Write);

      StreamReader sr = new StreamReader(f1);

      StreamWriter sw = new StreamWriter(f2);

   // position the file pointer at beginning of the file

                sr.BaseStream.Seek(0, SeekOrigin.Begin);

              string str = sr.ReadLine();

     while(str)

      {

         sw.WriteLine(str);

         sw.Flush(0;

         str = sr.ReadLine();

        }

             sr.Close();

             sw.Close();

              f1.Close();

               f2.Close();

     }

public static void Main()

{

       FileCopy fc = new FileCopy();

         fc.copyfile();

}

}

Working with the Windows File System

The .Net framework provides few basic classes for retrieving the file system information. These classes help retrieving information about existing files and directories and performing typical file operations like copying files and creating directories.

The DirectoryInfo and FileInfo class

Both these classes are derived fro the FileSystemInfo class. So they share a common set of properties and methods.  Let us have a look into the common methods and properties first and then we will discuss the unique properties of both the classes.

Common DirectoryInfo and FileInfo members:

Member

Description

Attributes

Allows to retrieve or set attributes associated with the current directory or file

CreationTime, LastAccessTime, and LastWriteTime

Gets or sets the time of creation, last access or last write for the file or directory respectively using a DateTime object

Exists

Gets a Boolean value indicating whether the directory or file exists or not

FullName, Name and Extension

Gets a string containing the full path, name and file extension respectively for a file or directory

Delete()

Removes the file or directory

Refresh()

Updates the object to synchronize with any file system change

Create()

Creates the specified directory or file

MoveTo()

Copies the directory and its contents or the file.

Unique DirectoryInfo members:

Member

Description

Parent and Root

Returns a DirectoryInfo object presenting parent or root directory

CreateSubDirectory()

Creates a sub directory

GetDirectories()

Returns an array of DirectoryInfo object representing the directories in the current directory after matching all the criteria. It also allows to search subdirectories within directories

GetFiles()

Returns the files in the current directory, an array of FileInfo objects.

Unique FileInfo members:

Member

Description

Directory

Returns a DirectoryInfo object that represents the parent directory

DirectoryName

Returns a string indentifying the parent directory

Length

Gets the size of file in bytes

CopyTo()

Copies a file to the new path and filename specified as parameters.

Create() and CreateText()

Creates the file and returns a FileStream object and CreateText() returns a StreamWriter object that wraps the stream

Open(), OpenRead(), OpenText(), and OpenWrite()

Opens a file if it exists. OpenRead() and OpenText() open  a file in read only mode, returning a FileStream or StreamReader. OpenWrite() open a file in write only mode, returning a FileStream.

The following code shows the use of the above mentioned classes:

using System;

using System.IO;

namespace Files_in_window

{

 class FileChecker

   {

            public static void Main()

            {

           

            DirectoryInfo dirinfo = new DirectoryInfo(@"C:\WINDOWS");

//get all the files in the directory and their name and size

            FileInfo [] filelist = dirinfo.GetFiles();

            foreach (FileInfo file in filelist)

            Console.WriteLine( " File Name: {0}  Size:  {1} bytes", file.Name, file.Length );

            }

    }

}

 

The DriveInfo class

This class is new in .Net 2.0. It allows  retrieving information about a drive on your computer. It is typically used to retrieve information like total amount used and free space.

The members of the DriveInfo Class

Member

Description

TotalSize

Gets the total size of the drive in bytes

TotalFreeSpace

Gets total amount of free space in bytes

AvailableFreeSpace

Gets total amount of available space in bytes

DriveFormat

Return the name of the file system like NTFS or FAT32

DriveType

Returns a vlue from the DriveType enumeration indicating whether the drive type is fixed, network, CD_ROM,RAM or removable drive

IsReady

Returns a Boolean value stating whether the drive is ready for reading or writing

Name

Returns the drive letter name

VolumeLabel

Returns the descriptive volume label for the drive

RootDirectory

Returns a DirectoryInfo object for the root directory of the drive

GetDrives()

Retrieves an array of DriveInfo objects representing all the drives in your computer.

Conclusion:

Working with files is required both in web applications as well as desktop applications. In this article, I have tried to describe File handling using C#. It is a vast topic, so it was not possible to give an exhaustive description. Hope you find it useful.

Happy Programming!

About the Author

NAME: PIYALI SENGUPTA

QUALIFICATION: B.E., M.C.A

AREA OF INTEREST: WEB PROGRAMMING

HOBBIES: READING AND TRAVELLING

I HAVE MOSTLY WORKED AS A FACULTY. PRESENTLY WORKING FROM HOME.I LOVE MATHEMATICS, ALGORITHMS, PROGRAMMING, FRIENDS, CHILDREN AND NATURE NOT NECESSARILY IN THIS ORDER.YOU CAN CONTACT ME AT: [email protected]