0
0
C Sharp (C#)programming~5 mins

File class static methods in C Sharp (C#)

Choose your learning style9 modes available
Introduction

The File class static methods help you work with files easily without creating objects. You can create, read, write, copy, and delete files quickly.

When you want to read the contents of a text file to show it on screen.
When you need to save some data into a file for later use.
When you want to copy a file from one folder to another.
When you want to check if a file exists before using it.
When you want to delete a file you no longer need.
Syntax
C Sharp (C#)
File.MethodName(parameters);
File class methods are static, so you call them directly on the class without creating an object.
Common methods include ReadAllText, WriteAllText, Copy, Delete, and Exists.
Examples
Reads all text from a file named "example.txt" into a string.
C Sharp (C#)
string content = File.ReadAllText("example.txt");
Writes the text "Hello World!" into a file named "output.txt". If the file exists, it replaces the content.
C Sharp (C#)
File.WriteAllText("output.txt", "Hello World!");
Checks if the file "data.csv" exists and returns true or false.
C Sharp (C#)
bool exists = File.Exists("data.csv");
Copies "source.txt" to "backup.txt" and overwrites if "backup.txt" already exists.
C Sharp (C#)
File.Copy("source.txt", "backup.txt", overwrite: true);
Sample Program

This program writes text to a file, checks if it exists, reads and prints the content, copies the file, and then deletes the original file.

C Sharp (C#)
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "testfile.txt";

        // Write text to file
        File.WriteAllText(filePath, "Welcome to File class methods!");

        // Check if file exists
        if (File.Exists(filePath))
        {
            // Read text from file
            string content = File.ReadAllText(filePath);
            Console.WriteLine("File content:");
            Console.WriteLine(content);

            // Copy file
            string copyPath = "copy_testfile.txt";
            File.Copy(filePath, copyPath, overwrite: true);
            Console.WriteLine($"File copied to {copyPath}");

            // Delete original file
            File.Delete(filePath);
            Console.WriteLine($"Original file {filePath} deleted.");
        }
        else
        {
            Console.WriteLine("File does not exist.");
        }
    }
}
OutputSuccess
Important Notes

Always check if a file exists before reading or deleting to avoid errors.

When copying files, use the overwrite parameter carefully to avoid losing data.

File class methods work with paths, so ensure the path is correct and accessible.

Summary

File class static methods let you handle files easily without creating objects.

Common tasks include reading, writing, copying, checking existence, and deleting files.

Always handle files carefully to avoid errors or data loss.