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#
Method | Description |
Create | Using this method, you may create or replace it in the designated path. |
Open | Open 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. |
Copy | Copies a file with its characteristics and content intact from the source path to the target path. |
Decrypt | uses 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. |
Delete | Removes a file from the file system permanently by deleting it at the provided path. |
Move | Transfers 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. |
ReadAllLines | Use 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. |
ReadAllText | Opening a text file simplifies reading text-based files by reading the entire contents of the File and returning it as a string. |
WriteAllLines | Allows you to create or edit text files with many lines of content by writing an array of strings as lines to a file. |
WriteAllText | Writes a string to a file, making changing or creating new text-based files with a single string simple. |
ReadLines | To process big files line-by-line, this function reads every line from a file and returns it as an IEnumerable. |
WriteAllBytes | Allows you to create or update binary files with specific binary data by writing a byte array to a file. |
Replace | Replaces every instance of a given string in a file with a different string, simplifying text replacement procedures. |
Exists | Checks to see if a file is there at the given path, enabling you to confirm the existence of the File before executing activities. |
OpenWrite | Using 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. |
OpenRead | This 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#](https://static.tutorialandexample.com/csharp/file-class-in-csharp1.png)
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.
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#](https://static.tutorialandexample.com/csharp/file-class-in-csharp2.png)
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#](https://static.tutorialandexample.com/csharp/file-class-in-csharp3.png)
- 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#](https://static.tutorialandexample.com/csharp/file-class-in-csharp4.png)
- 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#](https://static.tutorialandexample.com/csharp/file-class-in-csharp5.png)
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.