File Handling in C#


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.

In C#, 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>);

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 get the directories.

Example

//creating a DirectoryInfo object
DirectoryInfo mydir = new DirectoryInfo(@"d:\Demo");

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

Updated on: 21-Jun-2020

499 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements