What are file operations in C#?


C# has the following file operations −

  • Create, open, read and write a file.
  • Append,
  • Delete, etc.

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 = new FileStream( <file_name>, <FileMode Enumerator>,
<FileAccess Enumerator>, <FileShare Enumerator>);

Here, the file operations are also included as shown below −

The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are −

  • Append − It opens an existing file and puts cursor at the end of 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.

FileAccess - The FileAccess enumerators have members −

  • Read,
  • ReadWrite and
  • Write.

FileShare - The FileShare enumerators have the following members −

  • Inheritable − It allows a file handle to pass inheritance to the child processes

  • None − It declines sharing of the current file

  • Read − It allows opening the file for readin.

  • ReadWrite − It allows opening the file for reading and writing

  • Write − It allows opening the file for writing

Let us see an example to create, open and read the contents of a file −

Example

 Live Demo

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();
      }
   }
}

Output

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1

Updated on: 20-Jun-2020

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements