Working With File Class In C#

In C#, ‘File’ class provides many static methods for moving, copying, and deleting files. These Static methods involve moving a file and copying and deleting a file also. Let’s check out the chart below.

List of the common File class methods:

Sr. No.Method NameDescription
1.CopyThis method is used to copy given file to the specified location.
2.CreateThis method is used to create a file in the specified path.
3.DeleteThis method is used to Delete a file.
4.OpenThis method is used to return a filestream object at the specified path.
5.MoveMoves a given file to a new location. We can also specify a different or new name for the file in the new location.
6.ExistsThis method is used to check whether the specified file exists or not. It returns boolean=true if file exists else will return false.
7.OpenWriteIt is used to opens an existing file or creates a new file for writing.
8.OpenReadIt is used to opens an existing file for reading.

File.Create Method:

The File.Create method is used to creates a file in the specified folder.

string filePath= @ "D:\Data\Student.txt";
FileStream fs = File.Create(filePath); 

    Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
    fs.Write(info, 0, info.Length);
    Console.WriteLine("File has been created");

File.Delete Method

The File.Delete method is used to deletes a file with the given name in a specified folder.

static void Main(string[] args) {
    string path = @ "D:\Data\Student.txt";
    File.Delete(path);
    Console.WriteLine("File has been deleted successfully.");
}

File.Open Method

This method is used to return a FileStream object at the specified path. 

FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Write, FileShare.None); 

The following example demonstrates some of the FileStream constructors.

using System;  
using System.IO;  
using System. Text;  
  
class TestClass  
{  
  
    public static void Main()  
    {  
        string path = @"c:\DATA\Student.txt";  
        // Delete the file if it exists.  
        if (File.Exists(path))  
        {  
            File.Delete(path);  
        }  
         //Create the file.  
        using (FileStream fs = File.Create(path))  
        {  
            AddText(fs, "This is some text");  
            AddText(fs, "This is some more text,");  
            AddText(fs, "\r\nand this is on a new line");  
            AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");  
  
            for (int i=1;i < 120;i++)  
            {  
                AddText(fs, Convert.ToChar(i).ToString());  
  
            }  
        }  
  
        //Open the stream and read it back.  
        using (FileStream fs = File.OpenRead(path))  
        {  
            byte[] b = new byte[1024];  
            UTF8Encoding temp = new UTF8Encoding(true);  
            while (fs.Read(b,0,b.Length) > 0)  
            {  
                Console.WriteLine(temp.GetString(b));  
            }  
        }  
    }  
  
    private static void AddText(FileStream fs, string value)  
    {  
        byte[] info = new UTF8Encoding(true).GetBytes(value);  
        fs.Write(info, 0, info.Length);  
    }  
}  

File.Exists Method:

This method determines whether the specified file exists.

static void Main(string[] args) {
    string path = @ "D:\Data\Student.txt";
    Console.WriteLine(File.Exists(path) ? "File exists." : "oops! File does not exist.");
}

File.Copy Method:

This method copies a file to the specified location.

static void Main(string[] args) 
{
    string path = @ "D:\data\student.txt";
    string path1 = @ "D:\DataNew\Sudent.txt";
    File.Copy(path, path1);
    Console.WriteLine("File has been copied, Well done.");
}

File.Move Method:

This method moves a specified file to a new location. We can specify a different name for the file in the new location:

static void Main(string[] args) 
{
    string path = @ "D:\MyTestFile1.txt";
    string path1 = @ "c:\MyTest1.txt";
    File.Move(path, path1);
    Console.WriteLine("File has been moved");
}

File.OpenRead method:

This method is used to opens an existing file for reading its data. Check more on multiple read methods of File class.

public static void Main() {
        string path = @ "d:\data\student.txt";
        if (!File.Exists(path)) {
            // Create the file.
            FileStream fs = File.Create(path); {
                Byte[] info = new UTF8Encoding(true).GetBytes("This is a file");
                fs.Write(info, 0, info.Length);
            }
        }
        using(FileStream fs = File.OpenRead(path)) {
            byte[] b = new byte[1024];
            UTF8Encoding temp = new UTF8Encoding(true);
            while (fs.Read(b, 0, b.Length) > 0) {
                Console.WriteLine(temp.GetString(b));
            }
        }

We hope in above post you have learned about the different methods of File class in C#. Please leave your comments and suggestions it will help us to improve our posts/content quality.

Leave a Reply

Your email address will not be published. Required fields are marked *