C# – File I/O

  • Post author:
  • Post category:C#
  • Post comments:1 Comment
C# - File I/O

C# File I/O 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 the output stream. The input stream is used for reading data from the file (read operation) and the output stream is used for writing into the file (write operation).

C# File 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 −

Sr.No.I/O Class & Description
1BinaryReaderReads primitive data from a binary stream.
2BinaryWriterWrites primitive data in binary format.
3BufferedStreamA temporary storage for a stream of bytes.
4DirectoryHelps in manipulating a directory structure.
5DirectoryInfoUsed for performing operations on directories.
6DriveInfoProvides information for the drives.
7FileHelps in manipulating files.
8FileInfoUsed for performing operations on files.
9FileStreamUsed to read from and write to any location in a file.
10MemoryStreamUsed for random access to streamed data stored in memory.
11PathPerforms operations on path information.
12StreamReaderUsed for reading characters from a byte stream.
13StreamWriterIs is used for writing characters to a stream.
14StringReaderIs is used for reading from a string buffer.
15StringWriterIs 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 named sample.txt as shown −

FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read,
   FileShare.Read);
Sr.No.Parameter & Description
1FileModeThe FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are −Append − It opens an existing file and puts the cursor at the end of the file, or creates the file if the file does not exist. Create − It creates a new file.CreateNew − It specifies to the operating system, that it should create a new file. Open − It opens an existing file.OpenOrCreate − It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file. Truncate − It opens an existing file and truncates its size to zero bytes.
2FileAccessFileAccess enumerators have members: ReadReadWrite, and Write.
3FileShareFileShare enumerators have the following members −Inheritable − It allows a filehandle to pass an inheritance to the child processes None − It declines to share of the current file read − It allows opening the file for reading.ReadWrite − It allows opening the file for reading and writing write − It allows opening the file for writing

Example

The following program demonstrates the 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.

Sr.No.Topic & Description
1Reading from and Writing into Text files (It involves reading from and writing into text files. The StreamReader and StreamWriter class help to accomplish it.)
2Reading from and Writing into Binary files (It involves reading from and writing into binary files. The BinaryReader and BinaryWriter class help to accomplish this.)
3Manipulating the Windows file system (It gives a C# programamer the ability to browse and locate Windows files and directories.)

Next Topic – Click Here

This Post Has One Comment

Leave a Reply