SoFunction
Updated on 2025-04-06

Summary of common file processing operations in C#

1. Manage files

The File class in C# can use the File class to read, write and delete files. The File class provides multiple static methods to process files, such as () to check whether the file exists, () to read the file content, () to write the file content, and () to delete the file, etc.

using System;
using ;

class Program
{
    static void Main()
    {
        // Output the current directory        string currentDirectory = ();
        ("Current directory: {0}", currentDirectory);
        // Create a new folder and display a message        string newFolder = (currentDirectory, "NewFolder");
        (newFolder);
        ("A new folder has been created: {0}", newFolder);
        // Create a new file and display a message        string newFile = (currentDirectory, "");
        (newFile, "Hello, World!");
        ("New file has been created: {0}", newFile);
        // Check whether the file exists and read the content        if ((newFile))
        {
            string fileContent = (newFile);
            ("File content: {0}", fileContent);
        }
        // Delete files and folders and display messages        (newFile);
        ("Deleted file: {0}", newFile);
        (newFolder);
        ("Deleted file夹: {0}", newFolder);
    }
}

2. Manage drives

The DriveInfo class can get information about drives on the computer, such as available space, volume labels, and drive types.

using System;
using ;

class Program
{
    static void Main()
    {
        DriveInfo[] allDrives = ();
        foreach (DriveInfo d in allDrives)
        {
            ("Drive {0}", );
            ("  Drive类型: {0}", );
            if ( == true)
            {
                ("  Coil label: {0}", );
                ("  File system: {0}", );
                ("  Current user available space:{0, 15} byte", );
                ("  Total available space:          {0, 15} byte", );
                ("  Drive总大小:            {0, 15} byte ", );
            }
        }
    }
}

3. Management Directory

The Directory class in C# can create, delete and traverse directories. The Directory class provides multiple static methods to process directories, such as () for creating directories, () for deleting directories, () for checking whether the directory exists, () for obtaining a list of subdirectories in a directory, () for obtaining a list of files in a directory, etc.

// Create a new directorystring newDirectory = (currentDirectory, "NewDirectory");
(newDirectory);
("A new directory has been created: {0}", newDirectory);
// Check whether the directory exists and get the subdirectory list and file listif ((newDirectory))
{
    string[] subDirectories = (newDirectory);
    ("Subdirectory list:");
    foreach (string subDir in subDirectories)
    {
        (subDir);
    }
    string[] files = (newDirectory);
    ("File List:");
    foreach (string file in files)
    {
        (file);
    }
}
// Delete the directory(newDirectory);
("Deleted directory: {0}", newDirectory);

4. Management path

In C#, you can use the Path class to perform path operations, including merging paths, getting file names and extensions, etc. The Path class provides multiple static methods to process paths, such as () for merging paths, () for getting file names, () for getting file extensions, etc.

// Merge path examplestring path1 = @"C:\Dir1";
string path2 = "Dir2";
string combinedPath = (path1, path2);
("Merged path: " + combinedPath);
// Get filename and extension examplestring filePath = @"C:\Dir1\";
string fileName = (filePath);
string fileExtension = (filePath);
("file name: " + fileName);
("File extension: " + fileExtension);

5. Obtain file information

Use the FileInfo class in C# to obtain detailed information of files, such as file size, creation time, modification time, etc. The FileInfo class provides multiple attributes and methods to obtain file information, such as the Length attribute is used to obtain file size, the CreationTime attribute and the LastWriteTime attribute are used to obtain file creation time and last modification time, respectively.

using System;
using ;

class Program
{
    static void Main()
    {
        try
        {
            string filePath = @"C:\example\";
            // Check whether the file exists            if ((filePath))
            {
                FileInfo fileInfo = new FileInfo(filePath);
                // Get the file name                string fileName = ;
                ("file name: " + fileName);
                // Get file size                long fileSizeInBytes = ;
                ("File size (byte): " + fileSizeInBytes);
                // Get the file extension                string fileExtension = ;
                ("File extension: " + fileExtension);
                // Get the file creation time                DateTime creationTime = ;
                ("Create time: " + creationTime);
            }
            else
            {
                ("The file does not exist");
            }
        }
        catch (Exception ex)
        {
            ("An error occurred: " + );
        }
    }
}

6. Control how to process files

In C#, you can use the File class and Directory class to control the processing of files and directories. Here are some common operations:

Read file content:

string text = (@"C:\example\");

Write file content:

string content = "Hello, World!";
(@"C:\example\", content);

Copy the file:

(@"C:\example\", @"D:\backup\", true);

Delete the file:

(@"C:\example\");

Check if the file exists:

if ((@"C:\example\"))
{
    // Processing logic when the file exists}

Create a directory:

(@"C:\example\newfolder");

Get all files in the directory:

string[] files = (@"C:\example");
foreach (string file in files)
{
    (file);
}

This is the end of this article about the common file processing operations summary in C#. For more related C# file processing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!