A file is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the input stream and theoutput stream. The input stream is used for reading data from file (read operation) and the output stream is used for writing into the file (write operation).
C# I/O Classes
The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc.
The following table shows some commonly used non-abstract classes in the System.IO namespace:
I/O Class | Description |
---|---|
BinaryReader | Reads primitive data from a binary stream. |
BinaryWriter | Writes primitive data in binary format. |
BufferedStream | A temporary storage for a stream of bytes. |
Directory | Helps in manipulating a directory structure. |
DirectoryInfo | Used for performing operations on directories. |
DriveInfo | Provides information for the drives. |
File | Helps in manipulating files. |
FileInfo | Used for performing operations on files. |
FileStream | Used to read from and write to any location in a file. |
MemoryStream | Used for random access to streamed data stored in memory. |
Path | Performs operations on path information. |
StreamReader | Used for reading characters from a byte stream. |
StreamWriter | Is used for writing characters to a stream. |
StringReader | Is used for reading from a string buffer. |
StringWriter | Is used for writing into a string buffer. |
The FileStream Class
The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.
You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows:
FileStream <object_name> = new FileStream( <file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);
For example, we create a FileStream object F for reading a file namedsample.txt as shown:
FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
Parameter | Description |
---|---|
FileMode |
The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are:
|
FileAccess |
FileAccess enumerators have members: Read, ReadWriteand Write.
|
FileShare |
FileShare enumerators have the following members:
|
Example
The following program demonstrates use of the FileStream class:
using System; using System.IO; namespace FileIOApplication { class Program { static void Main(string[] args) { FileStream F = new FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite); for (int i = 1; i <= 20; i++) { F.WriteByte((byte)i); } F.Position = 0; for (int i = 0; i <= 20; i++) { Console.Write(F.ReadByte() + " "); } F.Close(); Console.ReadKey(); } } }
When the above code is compiled and executed, it produces the following result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
Advanced File Operations in C#
The preceding example provides simple file operations in C#. However, to utilize the immense powers of C# System.IO classes, you need to know the commonly used properties and methods of these classes.
Topic and Description | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Reading from and Writing into Text files
It involves reading from and writing into text files. The StreamReader andStreamWriter class helps to accomplish it.
The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.
The StreamReader Class
The StreamReader class also inherits from the abstract base class TextReader that represents a reader for reading series of characters. The following table describes some of the commonly used methods of the StreamReader class:
Example
The following example demonstrates reading a text file named Jamaica.txt. The file reads:
Down the way where the nights are gay And the sun shines daily on the mountain top I took a trip on a sailing ship And when I reached Jamaica I made a stop using System; using System.IO; namespace FileApplication { class Program { static void Main(string[] args) { try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("c:/jamaica.txt")) { string line; // Read and display lines from the file until // the end of the file is reached. while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { // Let the user know what went wrong. Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } Console.ReadKey(); } } }
Guess what it displays when you compile and run the program!
The StreamWriter Class
The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series of character.
The following table describes the most commonly used methods of this class:
For a complete list of methods, please visit Microsoft's C# documentation.
Example
The following example demonstrates writing text data into a file using the StreamWriter class:
using System; using System.IO; namespace FileApplication { class Program { static void Main(string[] args) { string[] names = new string[] {"Zara Ali", "Nuha Ali"}; using (StreamWriter sw = new StreamWriter("names.txt")) { foreach (string s in names) { sw.WriteLine(s); } } // Read and show each line from the file. string line = ""; using (StreamReader sr = new StreamReader("names.txt")) { while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } Console.ReadKey(); } } }
When the above code is compiled and executed, it produces the following result:
Zara Ali Nuha Ali | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Reading from and Writing into Binary files
It involves reading from and writing into binary files. The BinaryReader andBinaryWriter class helps to accomplish this.
The BinaryReader and BinaryWriter classes are used for reading from and writing to a binary file.
The BinaryReader Class
The BinaryReader class is used to read binary data from a file. ABinaryReader object is created by passing a FileStream object to its constructor.
The following table describes commonly used methods of the BinaryReaderclass.
The BinaryWriter Class
The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created by passing a FileStream object to its constructor.
The following table describes commonly used methods of the BinaryWriter class.
For a complete list of methods, please visit Microsoft C# documentation.
Example
The following example demonstrates reading and writing binary data:
using System; using System.IO; namespace BinaryFileApplication { class Program { static void Main(string[] args) { BinaryWriter bw; BinaryReader br; int i = 25; double d = 3.14157; bool b = true; string s = "I am happy"; //create the file try { bw = new BinaryWriter(new FileStream("mydata", FileMode.Create)); } catch (IOException e) { Console.WriteLine(e.Message + "\n Cannot create file."); return; } //writing into the file try { bw.Write(i); bw.Write(d); bw.Write(b); bw.Write(s); } catch (IOException e) { Console.WriteLine(e.Message + "\n Cannot write to file."); return; } bw.Close(); //reading from the file try { br = new BinaryReader(new FileStream("mydata", FileMode.Open)); } catch (IOException e) { Console.WriteLine(e.Message + "\n Cannot open file."); return; } try { i = br.ReadInt32(); Console.WriteLine("Integer data: {0}", i); d = br.ReadDouble(); Console.WriteLine("Double data: {0}", d); b = br.ReadBoolean(); Console.WriteLine("Boolean data: {0}", b); s = br.ReadString(); Console.WriteLine("String data: {0}", s); } catch (IOException e) { Console.WriteLine(e.Message + "\n Cannot read from file."); return; } br.Close(); Console.ReadKey(); } } }
When the above code is compiled and executed, it produces the following result:
Integer data: 25 Double data: 3.14157 Boolean data: True String data: I am happy | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Manipulating the Windows file system
It gives a C# programamer the ability to browse and locate Windows files and directories.
C# allows you to work with the directories and files using various directory and file related classes such as the DirectoryInfo class and the FileInfo class.
The DirectoryInfo Class
The DirectoryInfo class is derived from the FileSystemInfo class. It has various methods for creating, moving, and browsing through directories and subdirectories. This class cannot be inherited.
Following are some commonly used properties of the DirectoryInfo class:
Following are some commonly used methods of the DirectoryInfo class:
For a complete list of properties and methods, please visit Microsoft's C# documentation.
The FileInfo Class
The FileInfo class is derived from the FileSystemInfo class. It has properties and instance methods for creating, copying, deleting, moving, and opening of files, and helps in the creation of FileStream objects. This class cannot be inherited.
Following are some commonly used properties of the FileInfo class:
Following are some commonly used methods of the FileInfo class:
For complete list of properties and methods, please visit Microsoft's C# documentation.
Example
The following example demonstrates the use of the above-mentioned classes:
using System; using System.IO; namespace WindowsFileApplication { class Program { static void Main(string[] args) { //creating a DirectoryInfo object DirectoryInfo mydir = new DirectoryInfo(@"c:\Windows"); // getting the files in the directory, their names and size FileInfo [] f = mydir.GetFiles(); foreach (FileInfo file in f) { Console.WriteLine("File Name: {0} Size: {1}", file.Name, file.Length); } Console.ReadKey(); } } }
When you compile and run the program, it displays the names of files and their respective sizes in the Windows directory.
|