Professional Documents
Culture Documents
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.
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);
The Peek method is used to read the next character without consuming it, i.e the file pointer does not move ahead.
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);
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
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");
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
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
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. }
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.
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); } } }
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");
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(); } } }
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.
} }
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.
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.
Binary Reader and Writer Read and write primitive data types
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.
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)
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);
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
Table 4FileMode Enumeration values Values Read Write Purpose/Use Data can be read (retrieved) from the file Data can be added to the file
s.Close();
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.
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);
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());
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.