You are on page 1of 26

File Handling in c#:

Files & Folders


One of the ways of permanent storage of data is through files. A file is a collection of data stored on a secondary storage device, such as the Hard Disk. Every file has a name associated with it, such as Essay.txt. The name comprises of two parts the base name (in our case Essay) and the extension (txt). The portion before the period (.) is the base name whereas the one after it is the extension. A file name can also contain multiple periods Dr. No.avi. The most significant period is always the last one. So, in this case, the base name of the file would be Dr. No and the extension avi. The extension is what determines the type of the file. For example, a document has an extension of doc while a JPEG Image file has an extension of jpg. The base name is what we specify to identify that particular file. Files are contained in folders or directories. A directory itself can contain other files and folders, thus forming a hierarchy. Files within a folder (directory) need to have unique names. Files with same base name but different extensions are allowed. So, the file My File.txt and My File.doc can co-exist in a folder. The full path of the file marks its complete address on a machine. For instance, if the file Notepad.exe is contained inside the Windows directory of your C drive, its path would be C:\Windows\Notepad.exe. Likewise, if it were to be contained inside the System32 directory which in turn is present in the Windows directory, the full path would be C:\Windows\System32\Notepad.exe. Note: No two files on your computer can have the same full path.

Stream
A stream is a sequence of bytes travelling from a source to a destination over a communication medium. Streams can either be input or output. The input stream is used for reading while the output stream is used for writing. Note: This stream concept does not just apply to files. It holds true for communication over a network through sockets too.

File System Classes


.NET provides a lot of classes for handling files. These are contained in the System.IO namespace. Listed below are various classes under this 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 in the form of binary data from the

stream. StreamReader Is used to read characters from a byte stream. StringReader Is used to read data from a string buffer. Is used to write primitive data types in the form of binary data to the BinaryWriter stream. StreamWriter Is used to write characters to a byte stream. StringWriter Is used to write data to a string buffer. Is used to read primitive data types in the form of binary data from the file BinaryReader stream. StreamReader Is used to read characters from the a byte stream. DirectoryInfo Is used to perform operations on directories. FileInfo Is used to perform operations on files.

FileStream Class
The FileStream class resides under the System.IO namespace and is derived from the abstract class Stream. It supports random access through seeking. Before you begin reading from and writing to a file, an object of the FileStream class needs to initialized. The parameterized constructor of this class allows to create/open files and set up appropriate file sharing modes. Creating a new file.
FileStream fs = new FileStream ( "TestFile.txt", FileMode.Create, FileAccess.Write, FileShare.Read );

Note: The code is spanned across multiple lines for the sake of clarity. The first parameter to the constructor is the path to the file. In this case the new file will be created in the working directory of the application. A complete path such as C:\Program Files\Maxotek\Tutorials\C-Sharp\Lesson14\TestFile.txt can also be used. Backslash being the escape sequence starter would need to be escaped in the string. The code would look something like:FileStream fs = new FileStream ( "C:\\Program Files\\Maxotek\\Tutorials\\CSharp\\Lesson14\\TestFile.txt", FileMode.Create, FileAccess.Write, FileShare.Read );

Another way of doing this, is to use the @ character before the string. This prevents any escape sequence character as the backslash itself is taken as a normal character.
FileStream fs = new FileStream ( @"C:\Program Files\Maxotek\Tutorials\CSharp\Lesson14\TestFile.txt", FileMode.Create, FileAccess.Write, FileShare.Read );

The second parameter to the constructor is the FileMode enumeration. It can have any of the following values. File Mode Description Create Creates a new file or truncates the existing file. Creates a new file. If the file already exists, throws a CreateNew System.IO.IOException. Opens an existing file. Throws a System.IO.FileNotFoundException if Open the file does not exist. Opens an existing file or creates a new one. The difference between this OpenOrCreate mode and the Create mode is that it does not truncate the file. Opens the file and seeks to the end. A new file is created if the file does Append not exist. Opens an existing file and truncates its content so that the file size Truncate becomes zero. Attempting to read in this mode throws an exception. The third parameter is the FileAccess which specifies whether the file is to be opened for Reading (FileAccess.Read), Writing (FileAccess.Write) or both (FileAccess.ReadWrite). The last parameter is FileShare mode which states how the file will be shared. FileShare Mode Description Read Allows other handles to read from the file. Write Allows other handles to write to the file. Delete Allows subsequent deleting of the file. Inheritable Makes the file handle inheritable to child processes. Declines sharing of file. No other process can open the file until it is None closed. Note: The constructor is overloaded into many other forms which take various other types and combinations of parameters. The above form was one of the basic ones. Writing to the File

We use the StreamWriter class which is inherited from the abstract class TextWriter to write a series of characters. After opening the file in the appropriate mode (Write or ReadWrite in this case), a new object of the StreamWriter class is created. The object of the FileStream class is passed to it, thus associating the stream with the file. After this, the content can be written to the file by using the Write or the WriteLine method. WriteLine appends an end of line to the content. These two methods are highly overloaded to enable almost all built in data types to be directly written. Once you have done all the writing, make sure you close the file using the Close method. This ensures all the content is physically written to the file. For performance reasons, the write operation is buffered and sometimes the content might not be physically written to the file even after the Write method was called. To force all the buffers to be cleared and all buffered content to be written to the underlying stream (File in our case), use the Flush method.
1 2 3 4 5 6 7 8 9 10 11 12 FileStream fs = new FileStream ( "TestFile.txt", FileMode.Create, FileAccess.Write, FileShare.Read ); StreamWriter sw = new StreamWriter(fs); sw.Write("Hello World"); sw.Close(); fs.Close(); // Close the Stream // Close the File

Reading from a fie The StreamReader class is used to read a series of characters from a FilStream. This class is derived from the abstract class TextReader. Before reading, the file must be opened in the appropriate mode (Read or ReadWrite). To Read the next character or the next set of characters, use the Read method. This method has two forms. One that does not take any parameters and reads the next character. It returns the byte value of the character. The other one takes three parameters:

An array of characters The read characters are stored in the variable passed here. The index of the buffer at which to begin writing Maximum number of characters to read

The ReadLine method reads a line of characters and returns the result in the form of a string.
1 FileStream fs = new FileStream 2 ( 3 "TestFile.txt", 4 FileMode.Open,

5 6 7 8 9 10 11 12 13 14 15 16 17 18

);

FileAccess.Read, FileShare.Read

StreamReader sr = new StreamReader(fs); string str = sr.ReadLine(); while (str != null) { Console.WriteLine(str); str = sr.ReadLine(); } sr.Close(); fs.Close(); // Close the Stream // Close the File

The file pointer can be seeked to any position of the file using the BaseStream propertys Seek method. This method takes two parameters. The first, a byte offset relative to the Origin (second) parameter. This value can be either positive which moves the pointer down the file or negative which moves the file pointer upwards. The second parameter known as the Origin parameter indicates the reference point to obtain the new position. The permissible values are Begin, Current and End. The following line of code moves the file pointer to the 5th character from the beginning.
sr.BaseStream.Seek(5, SeekOrigin.Begin);

Moves the pointer to the start.


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

Moves the pointer to 5 characters ahead of the current position.


sr.BaseStream.Seek(5, SeekOrigin.Current);

Moves the pointer 5 characters backward from the current position.


sr.BaseStream.Seek(-5, SeekOrigin.Begin);

Moves the pointer to the end.


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

The Peek method is used to read the next character without consuming it, i.e the file pointer does not move ahead.

Implementing Binary Read & Write


The StreamReader and StreamWriter classes work with character data. In this mode everything is written as plain text. To implement binary operations, wherein a number

such as 327.68 would be written as a float value consuming four bytes and not just as plain text, we need to use the BinaryReader and BinaryWriter classes. They are very similar to their text counterparts except that no Line (ReadLine and WriteLine) methods are provided. The BinaryReader class also supports data type specific methods such as ReadInt32, ReadDouble, etc. These allow you to directly read the content from the file in the appropriate format. If we were to use the StreamReader class, we would have to convert the string to integer or double format using the Convert.ToInt32 and Convert.ToDouble methods. Writing to File
1 int MyNumber = 69; 2 BinaryWriter bw = new BinaryWriter(fs); 3 bw.Write(MyNumber);

Reading from file


1 BinaryReader br = new BinaryReader(fs); 2 int MyNumber = br.ReadInt32();

Implementing the Windows File System


Often we need to browse directories and locate files. Many such operations can be accomplished by using the two classes DirectoryInfo and FileInfo. Both of these are derived from the FileSystemInfo class. The tables below list some of the commonly used properties and methods corresponding to both of these classes. Properties of DirectoryInfo Class Property Attributes CreationTime Exists FullName LastAccessTime Name Description Gets or sets attributes associated with the current directory. Gets or sets the Creation time of the directory. Gets a Boolean value indicating whether the directory exists Gets a string containing the full path of the directory. Gets the last accessed time of the directory. Gets a string containing the name of the directory.

Methods of DirectoryInfo Class Method Description Create Creates a directory. Delete Deletes a directory. GetDirectories Returns the directories in the current directory. Supports filtering and

GetFiles

recursive listing. Returns the file in the current directory.

Properties of FileInfo class Property Attributes CreationTime Directory Exists Extension FullName LastAccessTime LastWriteTime Length Name Description Gets or sets the attributes associated with the current file. Gets or sets the CreationTime of the file. Gets an instance of the directory to which the file belongs to. Gets a Boolean value indicating whether the file exists. Gets a string containing the extension of the file. Gets a string containing the full path to the file. Gets the last access time of the file. Gets the time of the last wriiten activity on the file. Gets the length of the file in Bytes. Gets the name of the File.

Methods of FileInfo class Method Create AppendText Delete Open OpenRead Description Creates a new file. Appends a text to the file. Deletes the file. Opens the file. Opens a file in the read-only mode.

Creating Objects
Creating a DirectoryInfo or FileInfo object is very simple. The constructor takes the path to the file.
DirectoryInfo di = new DirectoryInfo("C:\\Windows"); FileInfo fi = new FileInfo("C:\\Windows\\Notepad.exe");

Listing All Files in a Directory


The following code snippet lists all the files in the C:\Windows directory.
1 2 3 4 5 6 DirectoryInfo di = new DirectoryInfo("C:\\Windows"); FileInfo[] fis = di.GetFiles(); foreach (FileInfo fi in fis) { Console.WriteLine(fi.Name); }

File handling in C#
File handling in C#

File handling is an unmanaged resource in your application system. It is outside your application domain (unmanaged resource). It is not managed by CLR. Data is stored in two ways, persistent and non-persistent manner. When you open a file for reading or writing, it becomes stream. Stream: Stream is a sequence of bytes traveling from a source to a destination over a communication path. The two basic streams are input and output streams. Input stream is used to read and output stream is used to write. The System.IO namespace includes various classes for file handling. The parent class of file processing is stream. Stream is an abstract class, which is used as the parent of the classes that actually implement the necessary operations. The primary support of a file as an object is provided by a .NET Framework class called File. This static class is equipped with various types of (static) methods to create, save, open, copy, move, delete, or check the existence of a file. Diagram to represent file-handling class hierarchy

Note: FileIno, DirectoryInfo and DriveInfo classes have instance methods. File, Directory, Path classes have static methods. The following table describes some commonly used classes in the System.IO namespace. Class Name FileStream BinaryReader BinaryWriter StreamReader StreamWriter StringReader StringWriter DirectoryInfo FileInfo Description It is used to read from and write to any location within a file It is used to read primitive data types from a binary stream It is used to write primitive data types in binary format It is used to read characters from a byte Stream It is used to write characters to a stream. It is used to read from a string buffer It is used to write into a string buffer It is used to perform operations on directories It is used to perform operations on files

Reading and writing in the text file StreamWriter Class The StreamWriter class in inherited from the abstract class TextWriter. The TextWriter class represents a writer, which can write a series of characters. The following table describes some of the methods used by StreamWriter class. Methods Close Description Closes the current StreamWriter object and the underlying stream Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream Writes to the stream Writes data specified by the overloaded parameters, followed by end of line

Flush Write WriteLine

Program to write user input to a file using StreamWriter Class using System; using System.Text; using System.IO;

namespace FileWriting_SW { class Program { class FileWrite { public void WriteData() { FileStream fs = new FileStream("c:\\test.txt", FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); Console.WriteLine("Enter the text which you want to write to the file"); string str = Console.ReadLine(); sw.WriteLine(str); sw.Flush(); sw.Close(); fs.Close(); } } static void Main(string[] args) { FileWrite wr = new FileWrite(); wr.WriteData(); } } } StreamReader Class The StreamReader class is inherited from the abstract class TextReader. The TextReader class represents a reader, which can read series of characters. The following table describes some methods of the StreamReader class. Methods Close Description Closes the object of StreamReader class and the underlying stream, and release any system resources associated with the reader Returns the next available character but doesn't consume it Reads the next character or the next set of characters from the stream Reads a line of characters from the current stream and returns data as a string Allows the read/write position to be moved to any position with the file

Peek Read ReadLine Seek

Program to read from a file using StreamReader Class using System; using System.IO;

namespace FileReading_SR { class Program { class FileRead { public void ReadData() { FileStream fs = new FileStream("c:\\test.txt", FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs); Console.WriteLine("Program to show content of test file"); sr.BaseStream.Seek(0, SeekOrigin.Begin); string str = sr.ReadLine(); while (str != null) { Console.WriteLine(str); str = sr.ReadLine(); } Console.ReadLine(); sr.Close(); fs.Close(); } } static void Main(string[] args) { FileRead wr = new FileRead(); wr.ReadData(); } } I hope that this article would have helped you in understanding file handling. }

(1)How to Read a Text File in C# Windows Forms Application?


Last week i wrote a tutorial about storing images in database and then retrieving them through Visual Studio (C#). Now, i am going to write about reading data from text files in a C# windows forms application. It is a very simple application and even if you are not familiar with or good at C#, you can still read data from a text file stored in your hard drive, successfully. First of all, create a text file on your desktop, you can create it anywhere in your hard drive. Name it Read Text or anything you like. Write some data in it. For instance i have written Hi this is Ali from techtoggle.com.Now, go to Microsoft Visual Studio (i am using the 2005 version) and create a Visual C# Windows Application and name it Read Text (you can name it anything you like). By default a windows form named Form1 will be displayed on your screen. Now just to make it more

presentable, change its text to Read Text From File from the properties section. Using the toolbox, drag and drop a textbox and two buttons on your form. Now, from the properties section, change the text of button1 to Get Text From File and also change its name from button1 to btngettext. Similarly change the text of button2 to Exit and change its name from button2 to btnexit. This is just to avoid confusion while coding. You can also change the back color of buttons or the text box from the properties section, only if you like to. Adjust the size of the form, text box and the buttons accordingly. Now, your form should look like this :

Now, double click the Get Text From File button to go to the code view. Add the following directive at the top.
using System.IO;

Now, paste the following code in the function for btngettext button click event.
StreamReader objstream = new StreamReader("C:\\Users\\Muhammad Ali\\Desktop\\Read Text.txt"); textBox1.Text = objstream.ReadLine();

Note that you will have to change the path accordingly as to which location the text file from which you are trying to read text, is saved. And if you want to read all the text and not just a single line in the text file just replace ReadLine with ReadToEnd in the above code. Now go to the design view, and double click the Exit button and paste the following code in the function for btnexit click event.
Application.Exit();

And Youre done. Yes, its that simple. Run the project and you will be able to read a text file.

(2)How to write a Text File in C# Windows Forms Application?


using System.IO; namespace WindowsFormsApplication1 { public partial class Form3 : Form {

public Form3() { InitializeComponent(); } private void Btnwritetotextfile_Click(object sender, EventArgs e) { //TextWriter tw = new StreamWriter("c:\\san.txt"); //string[] st = textBox1.Text.Split(new char[] { '\n' }); //for (int i = 0; i < st.Length; i++) //{ // tw.WriteLine(st[i].ToString().Trim()); //} //tw.Close(); string[] movies={"Aathavan","Golden Eye","Omen"}; File.WriteAllLines("c:\\san.txt",movies); } } }

(3) Text file Reading and Writing in C#


This program below demonstrates the use of StreamWriter and StreamReader (both derive form the abstract type TextWriter and TextReader respectively). The .Net Framework has simple solutions to work with files. When working with text files there are usually three common steps: 1- Opening the file 2- Reading/Writing 3- Closing it Now, lets take a look at this example:
using using using using System; System.Collections.Generic; System.Text; System.IO;

namespace ConsoleApplication { class Program {

public static void Main(string[] args) {

//C# Code for writing into a file we call: File.txt

FileInfo f = new FileInfo("File.txt"); StreamWriter Text = f.CreateText(); //Insert text in separate lines Text.WriteLine("-->Line One content"); Text.WriteLine("--->Line Two Content");

//Insert text but does not create a new line Text.Write("---->Line Three "); Text.WriteLine("Content");

//To create new Line. Text.Write(Text.NewLine); Text.WriteLine(System.DateTime.Now); Text.Close();

//Calling the method to read File.txt readFiles();

Console.Read();

} public static void readFiles() { //We open File.txt StreamReader sr = new StreamReader("File.txt"); string lines = null; //Here we do a while loop in order to look for none empty lines. while ((lines = sr.ReadLine()) != null) { Console.WriteLine(lines); } sr.Close(); } } }

(4) File Handling in C#:


You can use C# to store data in text and binary files and write programs to read the data from the files. Writing to a File
public class WriteFile {

public WriteFile() { StreamWriter myFile = File.CreateText("hello.txt"); myFile.WriteLine("Hello"); myFile.WriteLine("This is a text file"); myFile.WriteLine("Goodbye"); myFile.Close(); } }

To work with files make sure that you have the System.IO namespace available to your code. This namespace gives you access to the File and StreamWriter classes which provide useful services for creating and manipulating files. Notice that you don't have to create a new object instance of the StreamWriter class In the example above, the text file that is created is called 'hello.txt' although any valid filename can be used. The WriteLine() method of the StreamWriter class is used to save the data and works in the same way as the equivalent method of the Console class, including outputting values stores in variables using he {0} placeholders. When you run your program the file will be created in the same location as where the program executable is located, which will be /bin/debug/ folder or /bin/release/ folder.

Reading from a file


Now that you have a file on disc, you will want to open the file and read the data.
public class ReadFile { public ReadFile() { string text; if (File.Exists("hello.txt")) {

} }

StreamReader myFile = File.OpenText("hello.txt"); while ((text = myFile.ReadLine()) != null) { Console.WriteLine(text); } myFile.Close(); } else { Console.WriteLine("File does not exists"); }

We use the StreamReader class to perform the read operations. The text file is read into the object and then the ReadLine() method is used to read each line into the 'text' variable until the end of the file is found.

Checking if a file exists


A simple addition to the above will allow you to check if a file exists before you perform any operations on it. The static method of the File class called Exists() returns a Boolean value indicating whether or not the specified file, and or file path, exists.

An alternative to Text Files : Binary Files


Storing data in binary format is a method that you may want to use when you have large text files. Binary files are smaller and so more efficient than text files.
//Write a binary file public class WriteFileBinary { public WriteFileBinary() { string name; int[] scores = new int[3]; Console.WriteLine("Enter your student name :"); name = Console.ReadLine(); for (int i = 0; i < 3; i++) { Console.WriteLine("Enter score {0} ", i+1); scores[i] = Convert.ToInt32(Console.ReadLine()); }

FileStream myFile = new FileStream("hello.bin", FileMode.Create); BinaryWriter filedata = new BinaryWriter(myFile); filedata.Write(name); for (int i = 0; i < 3; i++) { filedata.Write(scores[i]); } filedata.Close(); myFile.Close(); } } //Read a binary file public class ReadFileBinary { public ReadFileBinary() { string name; int[] scores = new int[3]; FileStream myFile = new FileStream("hello.bin", FileMode.Open); BinaryReader filedata = new BinaryReader(myFile); name = filedata.ReadString(); for (int i = 0; i < 3; i++) { scores[i] = filedata.ReadInt32(); } filedata.Close(); myFile.Close(); Console.WriteLine("Information from file"); Console.WriteLine("Name {0} :", name); for (int i = 0; i < 3; i++) { Console.WriteLine("Score {0}, {1}", i + 1, scores[i]); } } }

The above two classes illustrate using the BinaryReader and BinaryWriter classes. It also uses the FileStream class to handle the opening and closing of the files. The FileStream constructor takes two arguments : the name of the file and the method of opening it. The possible methods of the FileMode paramenter are :

Append - opens an exisiting or creates a new file if it is not found Create - creates a new file, deleting an existing file of the same name, if it exists. CreateNew - creates a new file but does not delete it if it already exists. Open - opens an existing file. OpenOrCreate - opens an existing file and creates it if it does not exist. Truncate - opens an existing file and deletes the contents.

Note how the BinaryWriter class is used to Write the data to the file and the BinaryRead data is used to Read the data from the file. The process of writing to a file is not difficult but the process of reading the data back could become complicated because you have to read the data into the correct datatypes. The examples above do not include exception handling which should be used to check if the file was created and checking of datatypes when the data is read into the variables.

(5) Working with Files in C#


The Namespace
System.IO provides all the necessary classes, methods, and properties for manipulating directories and files. Table 1 elaborates the main classes under this namespace. Class Directory, File, DirectoryInfo, and FileInfo FileStream MemoryStream StreamWriter and StreamReader StringReader and StringWriter Purpose/Use Create, delete, and move files and directories. Get specific information about the files by making use of the properties defined in these classes. Access the files in a random fashion Access data stored in memory Read and write textual information Read and write textual Information from a string buffer

Binary Reader and Writer Read and write primitive data types

Table 1Classes under System.IO

Working with DirectoryInfo and FileInfo classes


The base class of DirectoryInfo and FileInfo is FileSystemInfo. This is an abstract class, meaning you can't instantiate this class. But you can use the properties defined by this class. Table 2 elaborates its properties and methods. Properties Attributes CreationTime Exists Extension FullName LastWriteTime Name Delete() Purpose/Use Returns attributes associated with a file. Takes FileAttributes enumeration values Returns the time of creation of the file Checks whether a supplied file is a directory or not Returns the file extension Returns the full path of the file Returns the time of last written activity to the file Returns the name of a given file Deletes a file. Be careful when using this method.

LastAccessTime Returns last accessed time of the file

Table 2Members of FileSystemInfo class The DirectoryInfo class provides methods for creating, moving, and deleting directories. To make use of the above properties, create an object of the DirectoryInfo class as shown in Listing 1: Listing 1
DirectoryInfo dir1 = new DirectoryInfo(@"F:\WINNT");

You then can access the properties by using the object dir1, as shown in the code fragment in Listing 2: Listing 2
Console.WriteLine("Full Name is : {0}", dir1.FullName); Console.WriteLine("Attributes are : {0}", dir1.Attributes.ToString());

You can also apply the values of FileAttributes enumeration. Its values are shown in Table 3.

Properties Archive Directory Encrypted Hidden Offline ReadOnly System

Purpose/Use Returns the file's Archive status Returns whether the file is a directory or not Returns whether the file is encrypted or not Returns whether the file is hidden or not Signifies that the data is not available Indicates that the file is read only Indicates that the file is a System file (probably a file under the Windows folder)

Compressed Returns whether the file is compressed or not

Table 3FileAttributes Enumeration Values

Working with Files under a Directory


Suppose that you want to list all BMP files under the f:\Pictures directory. You can write a code as shown in the code snippet given in Listing 3: Listing 3
DirectoryInfo dir = new DirectoryInfo(@"F:\WINNT"); FileInfo[] bmpfiles = dir.GetFiles("*.bmp); Console.WriteLine("Total number of bmp files", bmpfiles.Length); Foreach( FileInfo f in bmpfiles) { Console.WriteLine("Name is : {0}", f.Name); Console.WriteLine("Length of the file is : {0}", f.Length); Console.WriteLine("Creation time is : {0}", f.CreationTime); Console.WriteLine("Attributes of the file are : {0}", f.Attributes.ToString()); }

Creating Subdirectories
You can easily create a subdirectory. Listing fragment 4 describes how to create a subdirectory called MySub under the Sub directory. Listing 4
DirectoryInfo dir = new DirectoryInfo(@"F:\WINNT"); try { dir.CreateSubdirectory("Sub"); dir.CreateSubdirectory(@"Sub\MySub"); } catch(IOException e)

{ }

Console.WriteLine(e.Message);

Creating Files by Using the FileInfo Class


With the FileInfo class, you can create new files, access information about the files, delete, and move files. This class also provides methods for opening, reading from, and writing to a file. Listing 5 shows how to create a text file and access its information like its creation time, full name, and so forth. Listing 5
FileInfo fi = new FileInfo(@"F:\Myprogram.txt"); FileStream fstr = fi.Create(); Console.WriteLine("Creation Time: {0}",f.CreationTime); Console.WriteLine("Full Name: {0}",f.FullName); Console.WriteLine("FileAttributes: {0}",f.Attributes.ToString()); //Way to delete Myprogram.txt file. Console.WriteLine("Press any key to delete the file"); Console.Read(); fstr.Close(); fi.Delete();

Understanding the Open() Method


The FileInfo class defines a method named Open() with which you can create files by applying the values of the FileMode and FileAccess enumerations. The code snippet in Listing 6 describes its usage: Listing 6
FileInfo f = new FileInfo("c:\myfile.txt"); FileStream s = f.Open(FileMode.OpenorWrite, FileAccess.Read);

You then can read from and write to a file by using the object 's'. In the overloaded Open() method, permission is given only for reading from a file. If you want to write to a file, you have to apply the ReadWrite value of FileAccess enumeration. Tables 4 and 5 describe the values of the FileMode and FileAccess enumerations. Values Append Create CreateNew Purpose/Use Opens the file and adds data. This should be used with the FileAccess Write Enumeration value. Creates a new file. Overwrites any existing file. Creates a new file. If the file already exists, IOException is thrown.

Open Truncate

Opens an existing file Truncates an existing file

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

Table 4FileMode Enumeration values Values Read Write Purpose/Use Data can be read (retrieved) from the file Data can be added to the file

ReadWrite Data can be added to and retrieved from the file

Table 5FileAccess Enumeration values

Writing to a Text File by Using the StreamWriter Class


You can easily write texts or other information to a file by using the CreateText() method of the FileInfo class. However, you have to obtain a valid StreamWriter. It's this StreamWriter reference that provides the required functionalities for writing to a file. To illustrate, Listing 7 writes a series of texts to the Mytext.txt file. Listing 7
FileInfo f = new FileInfo("Mytext.txt") StreamWriter w = f.CreateText(); w.WriteLine("This is from"); w.WriteLine("Chapter 6"); w.WriteLine("Of C# Module"); w.Write(w.NewLine); w.WriteLine("Thanks for your time"); w.Close();

Reading from a Text File


You can read from a Text file by using the StreamReader class. For this, you have to specify the file name using the static OpenText() method of the File class. Listing 8 reads the contents that we have written in Listing 7: Listing 8
Console.WriteLine("Reading the contents from the file"); StreamReader s = File.OpenText("Mytext.txt"); string read = null; while ((read = s.ReadLine()) != null) { Console.WriteLine(read); }

s.Close();

How To: Reading and Writing Text Files


by Joe Mayo, 2/17/02

Introduction
Text files provide a common denominator format where both people and programs can read and understand. The .NET Framework includes convenience classes that make reading and writing text files very easy. The following sequence outlines the basic steps necessary to work with text files: 1. Open the file 2. Read/Write to the file 3. Close the file It's that simple. Listing 1 shows how to write text data to a file.

Writing to a Text File


Listing 1: Writing Text Data to a File: TextFileWriter.cs
using System; using System.IO; namespace csharp_station.howto { class TextFileWriter { static void Main(string[] args) { // create a writer and open the file TextWriter tw = new StreamWriter("date.txt"); // write a line of text to the file tw.WriteLine(DateTime.Now); // close the stream tw.Close(); } } }

This program creates a text file when it runs. In the directory where the executable program is located, you'll find a file named date.txt. If you view the contents of this file, you'll see the following textual representation of the date and time when the program last ran:

2/15/2002 8:54:51 PM

The first task in Listing 1 is to open the file. This happens by instantiating a StreamWriter class, which returns an object of type TextWriter. The result could have also been assigned to a StreamWriter instance. The StreamWriter was called with a single parameter, indicating the name of the file to open. If this file doesn't exist, the StreamWriter will create it. The StreamWriter also has 6 other constructor overloads that permit you to specify the file in different ways, buffer info, and text encoding. Here's the line that opens the date.txt file:
TextWriter tw = new StreamWriter("date.txt");

Using the TextWriter instance, tw, you can write text info to the file. The example writes the text for the current date and time, using the static Now property of the DateTime class. Here's the line from the code:
tw.WriteLine(DateTime.Now);

When you're done writing to the file, be sure to close it as follows:


tw.Close();

Reading From a Text File


Listing 2 shows how to read from a text file:

Listing 2: Reading Text Data from a File: TextFileReader.cs


using System; using System.IO; namespace csharp_station.howto { class TextFileReader { static void Main(string[] args) { // create reader & open file Textreader tr = new StreamReader("date.txt"); // read a line of text Console.WriteLine(tr.ReadLine()); // close the stream tr.Close(); } } }

In Listing 2, the text file is opened in a manner similar to the method used in Listing 1, except it uses a StreamReader class constructor to create an instance of a Textreader. The StreamReader class includes additional overloads that allow you to specify the file in different ways, text format encoding, and buffer info. This program opens the date.txt file, which should be in the same directory as the executable file:
Textreader tr = new StreamReader("date.txt");

Within a Console.WriteLine statement, the program reads a line of text from the file, using the ReadLine() method of the Textreader instance. The Textreader class also includes methods that allow you to invoke the Read() method to read one or more character or use the Peek() method to see what the next character is without pulling it from the stream. Here's the code that reads an entire line from the text file:
Console.WriteLine(tr.ReadLine());

When done reading, you should close the file as follows:


tr.Close();

Summary
This article showed how to write text to a file and read it back out. For more details on additional methods, consult the .NET Frameworks reference on the StreamWriter, StreamReader, TextWriter, and Textreader classes.

You might also like