深入理解C#中的文件系统I/O操作

文件系统I/O操作是任何编程语言中的重要组成部分,C#也不例外。无论是读写文件、操作目录,还是处理文件流,C#都提供了丰富且强大的类库来实现这些功能。本文将详细介绍C#中的文件系统I/O操作,并通过代码示例展示如何高效地处理文件和目录。

1. 读写文件
写入文件

在C#中,可以使用System.IO命名空间下的File类来进行文件写入操作。

示例:

cs 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";
        string content = "这是一个示例文本。";

        // 写入文件
        File.WriteAllText(path, content);
        Console.WriteLine("文件写入成功。");
    }
}
读取文件

同样,我们也可以使用File类来读取文件内容:

cs 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example.txt";

        if (File.Exists(path))
        {
            // 读取文件内容
            string content = File.ReadAllText(path);
            Console.WriteLine("文件内容:");
            Console.WriteLine(content);
        }
        else
        {
            Console.WriteLine("文件不存在。");
        }
    }
}
2. 使用文件流

文件流提供了一种更灵活的文件读写方式,特别是在处理大文件时,文件流能够逐字节地读写数据,从而避免内存占用过高。

使用FileStream写入文件
cs 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "filestream_example.txt";
        byte[] data = System.Text.Encoding.UTF8.GetBytes("通过FileStream写入的数据。");

        using (FileStream fs = new FileStream(path, FileMode.Create))
        {
            fs.Write(data, 0, data.Length);
            Console.WriteLine("数据已通过FileStream写入。");
        }
    }
}
使用FileStream读取文件
cs 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "filestream_example.txt";

        using (FileStream fs = new FileStream(path, FileMode.Open))
        {
            byte[] data = new byte[fs.Length];
            fs.Read(data, 0, data.Length);
            string content = System.Text.Encoding.UTF8.GetString(data);
            Console.WriteLine("通过FileStream读取的内容:");
            Console.WriteLine(content);
        }
    }
}
3. 操作目录
创建目录

在C#中,可以使用Directory类来创建目录:

cs 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string dirPath = "example_directory";

        if (!Directory.Exists(dirPath))
        {
            Directory.CreateDirectory(dirPath);
            Console.WriteLine("目录创建成功。");
        }
        else
        {
            Console.WriteLine("目录已存在。");
        }
    }
}
删除目录

可以使用Directory类来删除目录:

cs 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string dirPath = "example_directory";

        if (Directory.Exists(dirPath))
        {
            Directory.Delete(dirPath, true);
            Console.WriteLine("目录已删除。");
        }
        else
        {
            Console.WriteLine("目录不存在。");
        }
    }
}
4. 遍历文件和目录
获取目录中的文件列表

可以使用Directory类获取指定目录中的文件列表:

cs 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string dirPath = "example_directory";

        if (Directory.Exists(dirPath))
        {
            string[] files = Directory.GetFiles(dirPath);
            Console.WriteLine("目录中的文件:");
            foreach (string file in files)
            {
                Console.WriteLine(file);
            }
        }
        else
        {
            Console.WriteLine("目录不存在。");
        }
    }
}
递归遍历目录

可以使用递归算法遍历目录及其子目录中的所有文件:

cs 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string dirPath = "example_directory";

        if (Directory.Exists(dirPath))
        {
            TraverseDirectory(dirPath);
        }
        else
        {
            Console.WriteLine("目录不存在。");
        }
    }

    static void TraverseDirectory(string dirPath)
    {
        string[] files = Directory.GetFiles(dirPath);
        string[] directories = Directory.GetDirectories(dirPath);

        foreach (string file in files)
        {
            Console.WriteLine("文件: " + file);
        }

        foreach (string directory in directories)
        {
            Console.WriteLine("目录: " + directory);
            TraverseDirectory(directory); // 递归遍历子目录
        }
    }
}
5. 文件属性操作

在文件系统操作中,读取和设置文件属性是一个常见需求。C#提供了FileInfo类来实现这一功能。

读取文件属性
cs 复制代码
using System;
using System.IO;

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

        FileInfo fileInfo = new FileInfo(filePath);

        if (fileInfo.Exists)
        {
            Console.WriteLine("文件名: " + fileInfo.Name);
            Console.WriteLine("文件路径: " + fileInfo.FullName);
            Console.WriteLine("文件大小: " + fileInfo.Length);
            Console.WriteLine("创建时间: " + fileInfo.CreationTime);
            Console.WriteLine("最后访问时间: " + fileInfo.LastAccessTime);
            Console.WriteLine("最后修改时间: " + fileInfo.LastWriteTime);
        }
        else
        {
            Console.WriteLine("文件不存在。");
        }
    }
}
设置文件属性
cs 复制代码
using System;
using System.IO;

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

        FileInfo fileInfo = new FileInfo(filePath);

        if (fileInfo.Exists)
        {
            // 设置文件属性
            fileInfo.Attributes = FileAttributes.ReadOnly;
            Console.WriteLine("文件属性已设置为只读。");

            // 恢复文件属性
            fileInfo.Attributes = FileAttributes.Normal;
            Console.WriteLine("文件属性已恢复为正常。");
        }
        else
        {
            Console.WriteLine("文件不存在。");
        }
    }
}
6. 异步文件I/O操作

在处理大文件或进行耗时的文件操作时,使用异步方法可以提高应用程序的响应性。C#提供了异步方法来进行文件的读写操作。

异步写入文件
cs 复制代码
using System;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string path = "async_example.txt";
        string content = "这是一个异步写入示例。";

        await File.WriteAllTextAsync(path, content);
        Console.WriteLine("文件异步写入成功。");
    }
}
异步读取文件
cs 复制代码
using System;
using System.IO;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        string path = "async_example.txt";

        if (File.Exists(path))
        {
            string content = await File.ReadAllTextAsync(path);
            Console.WriteLine("文件内容:");
            Console.WriteLine(content);
        }
        else
        {
            Console.WriteLine("文件不存在。");
        }
    }
}
7. 文件监视

C#提供了FileSystemWatcher类,用于监视指定目录中的文件或目录的更改。这在需要对文件系统变化做出响应的应用程序中非常有用。

使用FileSystemWatcher监视文件变化
cs 复制代码
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = "example_directory";

        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = path;
        watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size;
        watcher.Filter = "*.*";

        watcher.Changed += OnChanged;
        watcher.Created += OnChanged;
        watcher.Deleted += OnChanged;
        watcher.Renamed += OnRenamed;

        watcher.EnableRaisingEvents = true;

        Console.WriteLine("正在监视目录: " + path);
        Console.WriteLine("按任意键退出...");
        Console.ReadKey();
    }

    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        Console.WriteLine($"文件: {e.FullPath} {e.ChangeType}");
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        Console.WriteLine($"文件: {e.OldFullPath} 重命名为 {e.FullPath}");
    }
}

希望这些内容对你有所帮助,感谢阅读!

相关推荐
学习使我变快乐2 小时前
C++:const成员
开发语言·c++
Starry_hello world3 小时前
二叉树实现
数据结构·笔记·有问必答
500了3 小时前
Kotlin基本知识
android·开发语言·kotlin
不知所云,5 小时前
qt cmake自定义资源目录,手动加载资源(图片, qss文件)
开发语言·qt
安冬的码畜日常5 小时前
【玩转 JS 函数式编程_006】2.2 小试牛刀:用函数式编程(FP)实现事件只触发一次
开发语言·前端·javascript·函数式编程·tdd·fp·jasmine
阑梦清川5 小时前
Java继承、final/protected说明、super/this辨析
java·开发语言
PythonFun6 小时前
Python批量下载PPT模块并实现自动解压
开发语言·python·powerpoint
Death2006 小时前
Qt 6 相比 Qt 5 的主要提升与更新
开发语言·c++·qt·交互·数据可视化
机器视觉知识推荐、就业指导6 小时前
使用Qt实现实时数据动态绘制的折线图示例
开发语言·qt
快乐就好ya7 小时前
Java多线程
java·开发语言