C# Tutorial

C# Tutorial C# First Application C# Variables C# Data Types C# Operators C# Keywords

C# Control Statement

C# If Statements C# Switch Statements C# for Loop C# While Loop C# do While loop C# Jump Statements C# Function C# functions with out variable

C# Arrays

C# Arrays

C# Function

C# Function call by value C# Call by reference C# Passing array to function C# Multidimensional Arrays C# Jagged Arrays C# Params C# Array Class C# Command Line Arguments

C# Object Class

C# Object and Classes C# Constructors C# Destructor C# this Keyword C# static field C# static class C# Static Constructor C# Structs C# enum C# Properties

C# Inheritance

C# Inheritance C# Multilevel Inheritance C# Aggregation C# Member overloading C# Method Overriding C# Base

C# Polymorphism

C# Polymorphism C# Sealed

C# Abstraction

C# Abstraction C# Interface

C# Namespace

C# Namespace C# Access Modifiers C# Encapsulation

C# Strings

C# String

C# Misc

C# Design Patterns Dictionary in C# Boxing and Unboxing in C# Ref and Out in C# Serialization in C# Dispose and Finalize in C# CONSOLE LOG IN C# Get File extension in C# Insert query in c# Difference Between List and Dictionary in C# Getters and Setters in C# Extension Methods in C# Insert query in c# CONSOLE LOG IN C# Get File extension in C# Random.NextDouble() Method in C# Binary Search in C# Difference between Delegates and Interfaces in C# Double.IsFinite() Method in C# Index Constructor in C# Abstraction in C# Basic OOPS Concepts In C# Queue.CopyTo() Method in C# single.compareto() method in C# C# Throw Exception in Constructor DECODE IN C# file.setlastwritetimeutc() method in C# Convert Object to List in C# convert.ToSByte(string, IFormatProvider) Method in C# C# Declare Delegate in Interface console.TreatControl C As Input property in C# Copying the queue elements to 1-D Array in C# Array.Constrainedcopy() Method in C# C# in and out Char.IsLetterOrDigit() method in C# Debugging in C# decimal.compare() method in C# Difference between Console.Read and Console.Readline in C# Metadata in C# C# Event Handler Example Default Interface Methods in C# Difference between hashtable and dictionary in C# C# program to implement IDisposable Interface Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File C# Error Logging C# ENCRIPTION Can we create an object for Abstract Class in C# Console.CursorVisible in C# SortedDictionary Implementation in C# C# Hash Table with Examples Setting the Location of the Label in c# Collections in c# Virtual Keyword in C# Reverse of string in C# String and StringBuilder in C# Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File Difference between ref and out in C# Singleton Class in C# Const And Readonly In Csharp BinaryReader and BinaryWriter in C# C# Attributes C# Delegates DirectoryInfo Class in C# Export and Import Excel Data in C# File Class in C# FileInfo Class in C# How to Cancel Parallel Operations in C#? Maximum Degree of Parallelism in C# Parallel Foreach Loop in C# Parallel Invoke in C# StreamReader and StreamWriter in C# TextReader and TextWriter in C# AsQueryable() in C# Basic Database Operations Using C# C# Anonymous Methods C# Events C# Generics C# Indexers C# Multidimensional Indexers C# Multithreading C# New Features C# Overloading of Indexers Difference between delegates and events in C# Operator overloading in C# Filter table in C# C# Queue with Examples C# Sortedlist With Examples C# Stack with Examples C# Unsafe Code File Handling in C# HashSet in C# with Examples List Implementation in C# SortedSet in C# with Examples C# in Depth Delegates and Events in C# Finally Block in C# How to Split String in C# Loggers in C# Nullable Types in C# REVERSE A STRING IN C# TYPE CASTING IN C# What is Generics in C# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# Atomic Methods Thread Safety and Race Conditions in C# Parallel LINQ in C# Design Principles in C# Difference Between Struct And Class In C# Difference between Abstraction and Encapsulation in C# Escape Sequence Characters in C# What is IOC in C# Multiple Catch blocks in C# Appdomain in C# Call back methods in C# Change Datetime format in C# Declare String array in C# Default Access Specifier in c# Foreach in LINQ C# How to compare two lists in C# How to Convert String to Datetime in c# How to get only Date from DateTime in C# Ispostback in asp net C# JSON OBJECT IN C# JSON STRINGIFY IN C# LAMBDA FUNCTION IN C# LINQ Lambda Expression in C# Microservices in C# MSIL IN C# Reference parameter in C# Shadowing(Method hiding) in C# Solid principles in C# Static Members in C# Task run in C# Transaction scope in C# Type Conversion in c# Unit of Work in C# Unit Test Cases in c# User Defined Exception in c# Using Keyword in C# Var Keyword in C# What is gac in C#

File Class in C#

The File class in C# has static methods for uncomplicated file operations and is a subclass of the System.IO namespace. You can carry out numerous actions with the help of this class, including reading from, writing to, deleting, relocating, copying, and checking the existence of files on the file system.

The fundamental file operations that we typically perform are as follows:

  • Reading: This operation is a fundamental read operation in which data is read from a file.
  • Writing: This operation is fundamental in which data is written to a file. All existing contents were removed from the File by default, and new content was written.
  • Appending: This procedure also involves writing data to a file. The sole distinction is that existing data in a file is not rewritten. The File's end is where the newly to-be-written data is added.

 File Class Methods on C#

MethodDescription
CreateUsing this method, you may create or replace it in the designated path.
OpenOpen gives a FileStream object that lets you read and write to the File while opening it in the desired mode, such as Read, Write, Append, etc.
CopyCopies a file with its characteristics and content intact from the source path to the target path.
Decryptuses a specific encryption technique to encrypt the contents of a file, rendering the data unusable without the proper decryption key.  
Encrypt Ensures that the data is recovered in its original, readable form by encrypting the contents of a file using a particular encryption technique.
DeleteRemoves a file from the file system permanently by deleting it at the provided path.
MoveTransfers a file from one file system to another, either inside the same file system or across file systems.
ReadAllBytes It allows you to work with binary data by reading all the files' bytes and returning them as a byte array.
ReadAllLinesUse the ReadAllLines function to open a file. It Reads every line from a file and returns them as an array of strings, making text-based material simple to access and modify.
ReadAllTextOpening a text file simplifies reading text-based files by reading the entire contents of the File and returning it as a string.
WriteAllLinesAllows you to create or edit text files with many lines of content by writing an array of strings as lines to a file.
WriteAllTextWrites a string to a file, making changing or creating new text-based files with a single string simple.
ReadLinesTo process big files line-by-line, this function reads every line from a file and returns it as an IEnumerable.
WriteAllBytesAllows you to create or update binary files with specific binary data by writing a byte array to a file.
ReplaceReplaces every instance of a given string in a file with a different string, simplifying text replacement procedures.
ExistsChecks to see if a file is there at the given path, enabling you to confirm the existence of the File before executing activities.
OpenWriteUsing it lets you write data into a file by opening it in write mode and returning a FileStream object.
OpenText This technique is used to read it to read text-based content from a file by opening it in text mode and returning a StreamReader object.
OpenReadThis technique lets you read data from a file by opening it in read-only mode and returning a FileStream object.

Let's see some programs using file class methods.

When working with files, remember that some methods may produce exceptions. As such, it is best practice to manage them using try-catch blocks.

  • Ensure your program has the appropriate access rights to read, write, and destroy files on the file system.

The program illustrates basic operations on files:

Example:

using SystemSystem;

using System.IO;

class Program1

{

    static void Main()

    {

        // Set the file path

        string filePath = "d:\example.txt";

        // Write content to the file

        string contentToWrite = "Hello, this is some content that will be written to the file!";

        File.WriteAllText(filePath, content to write);

        // Read the content from the File and display it

        string contentRead = File.ReadAllText(filePath);

        Console.WriteLine("Content read from the file:");

        Console.WriteLine(contented);

        // Append additional content to the file

        string additionalContent = "\nThis will be added to the end.";

        File.AppendAllText(filePath, additional content);

        // Read the updated content from the File and display it

        contentRead = File.ReadAllText(filePath);

        Console.WriteLine("\nUpdated content read from the file:");

        Console.WriteLine(contented);

        // Check if the File exists

        bool file exists = File.Exists(filePath);

        Console.WriteLine($"\nDoes the file exist? {fileExists}");

        // Copy the File to a new location

        string destination path = "example_copy.txt";

        File.Copy(filePath, destination path, true);

        string newFilePath = "new_example.txt";

        File.Move(filePath, newFilePath);

        // Check if the original File still exists after the move

        bool originalFileExists = File.Exists(filePath);

        Console.WriteLine($"\nDoes the original file still exist after moving? {originalFileExists}");

        // Check if the copied File exists at the new location

        bool copiedFileExists = File.Exists(destinationPath);

        Console.WriteLine($"\nDoes the copied File exist at the new location? {

copiedFileExists

}");

        Console.ReadLine();

    }

}

Output:

File Class in C#

This program is a sample example where working of files in the above program in the place of the files you can also replace with a directory of the file path.

  • The File class is used in this program to create, write to, read from, append to, check for the existence of, copy, and move files.
  •  It's critical to note that file operations may call for the proper permissions depending on where the program is operating.

Example:

The program checks Whether the File exists or not:

You may determine whether a file exists at the supplied path using the static File.Exists() function in C#. It provides a boolean result that indicates whether the File is there.

using SystemSystem;

using System.IO;

class Program

{

    static void Main()

    {

        string filePath = "D:\example.txt";

        if (File.Exists(filePath))

        {

            Console.WriteLine("The file exists.");

        }

        else

        {

            Console.WriteLine("The file does not exist.");

        }

    }

}

Output:

File Class in C#

To determine whether a specific file exists, utilize the Exists Method of the File Class in C#. If the caller has the correct rights and the path contains the name of an existent file, this function will return true; otherwise, it will return as false.

Copying Method file class:

An existing file can be copied using the static Copy Method of the File Class in C#.

Example:

using SystemSystem;

using System.IO;

class Program2

{

    static void Main()

    {

        string sourceFilePath = “D:\MyFile.txt”;

        string destinationFilePath = “D:\MyFileCopy.txt”;

        try

        {

            // Check if the source file exists

            if (File.Exists(sourceFilePath))

            {

                File.Copy(sourceFilePath, destinationFilePath);

                Console.WriteLine("File copied successfully.");

            }

            else

            {

                Console.WriteLine("The source file does not exist.");

            }

        }

        catch (IOException ex)

        {

            Console.WriteLine("An error occurred while copying  file: " + ex.Message);

        }

    }

}

Output:

File Class in C#
  • The main thing need to remember is that utilizing the Copy method of the File class to overwrite a file with the same name is not permitted. A different name must be used for the copy file.
  • There are two arguments for the Copy method. The first parameter is the source file name and the File to copy.
  • The destinationFileName file's name, is the second parameter. The destination file cannot be a directory and an existing file.

The program sets the destination file path (destinationFilePath) to be "D:\MyFileCopy.txt" and the source file path (sourceFilePath) to be "D:\MyFile.txt".

  • The File is then used. The source file supplied by sourceFilePath can be verified as existing using the Exists() function.
  •  In that case, the program will report, "The source file does not exist."

The program calls the File if the source file is there. Using the destinationFilePath-specified destination file, the source file's contents are copied using the Copy() method.

Delete Method class in C#:

In C#, the File class has a static function called File.Delete() that you can used to remove a file from the file class system. You can delete a particular file from the specified location using this technique also.

Example:

using SystemSystem;

using System.IO;

class Program3

{

    static void Main()

    {

        string filePath = "D:\myfile.txt";

        try

        {

            // Delete the File

            File.Delete(filePath);

            Console.WriteLine("File deleted successfully.");

        }

        catch (FileNotFoundException)

        {

            Console.WriteLine("The file does not exist.");

        }

        catch (IOException)

        {

            Console.WriteLine("An error occurred while deleting the file.");

        }

    }

}

Output:

File Class in C#
  • I am using a file.Delete(); the program attempts to remove the file "D:\myfile.txt". If the File is erased, the console will display "Deleted successfully."
  • The relevant exception will be caught and dealt with if the File does not exist or any other problem arises during the deletion procedure.

Note: When utilizing the File, use caution.Delete() technique, as there is no undo action, and the File is wholly removed from the SystemSystem.

  • Make that the program has the necessary rights to remove the File. An exception will be raised if the application lacks the required privileges/
  • Always handle exceptions correctly in your code to give users helpful feedback and stop unexpected crashes brought on by problems with file access.

Appending method file class in c#:

A direct method for adding content to an existing file does not exist in the C# File class. Use the File as an alternative.

The File class's static AppendAllText() method, which adds text to the end of a file, is available.

Example:

using SystemSystem;

using System.IO;

class Program4

{

    static void Main()

    {

        string filePath = "D:\mylog.txt";

        string additionalContent = "\nThis is the new content to append.";

        try

        {

            // Append content to the File

            File.AppendAllText(filePath, additional content);

            Console.WriteLine(“Content appended successfully.”);

        }

        catch (FileNotFoundException)

        {

            Console.WriteLine("The file does not exist.");

        }

        catch (IOException)

        {

            Console.WriteLine("An error occurred while a appending the content.");

        }

    }

}

Output:

File Class in C#

The software employs files. To add the additional content string to the end of the "mylog.txt" file, use AppendAllText().

  • A new line is added before the appended material by the n in additional content.
  • When this program is run, it will append new material to the already-existing File and show "Content appended successfully." on the console.

Note: if there is File doesn't already exist, the File.AppendAllText() method will creates. Consider utilizing the StreamWriter class with there FileMode. Append option if you require more control over the file stream, such as opening it with a specific encoding and parameters.