位置: 文档库 > C#(.NET) > C语言 文件操作解析详解及实例代码

C语言 文件操作解析详解及实例代码

建筑师 上传于 2021-01-29 14:24

《C语言 文件操作解析详解及实例代码》这一标题存在主题偏差,实际需求为C#(.NET)文件操作解析。以下将围绕C#(.NET)文件系统操作展开详细论述,涵盖基础概念、核心类库、典型场景及完整代码示例。

一、C#文件操作核心体系

在.NET框架中,文件操作主要通过System.IO命名空间下的类库实现,包含以下核心组件:

  • File类:提供静态方法进行文件创建、删除、读写等操作
  • FileInfo类:通过实例化对象管理单个文件属性
  • Directory类:处理目录相关操作
  • DirectoryInfo类:管理目录实例属性
  • Stream系列类:包括FileStreamMemoryStream等流式处理
  • StreamReader/StreamWriter:文本文件读写专用类

二、基础文件操作实现

1. 文件创建与写入

使用File.WriteAllText快速创建并写入文本文件:

string content = "这是C#文件操作示例";
string filePath = @"C:\Temp\demo.txt";
File.WriteAllText(filePath, content);

通过StreamWriter实现追加写入:

using (StreamWriter writer = new StreamWriter(filePath, true))
{
    writer.WriteLine("追加内容");
    writer.WriteLine(DateTime.Now.ToString());
}

2. 文件读取操作

一次性读取全部内容:

string fileContent = File.ReadAllText(filePath);
Console.WriteLine(fileContent);

逐行读取大文件:

string[] lines = File.ReadAllLines(filePath);
foreach (string line in lines)
{
    Console.WriteLine(line);
}
// 或使用StreamReader高效处理
using (StreamReader reader = new StreamReader(filePath))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

3. 文件信息管理

使用FileInfo获取详细属性:

FileInfo fileInfo = new FileInfo(filePath);
Console.WriteLine($"文件名: {fileInfo.Name}");
Console.WriteLine($"大小: {fileInfo.Length / 1024}KB");
Console.WriteLine($"创建时间: {fileInfo.CreationTime}");
Console.WriteLine($"扩展名: {fileInfo.Extension}");

三、高级文件操作场景

1. 二进制文件处理

使用FileStream读写图片文件:

// 写入二进制文件
byte[] imageData = File.ReadAllBytes(@"C:\input.jpg");
using (FileStream fs = new FileStream(@"C:\output.jpg", FileMode.Create))
{
    fs.Write(imageData, 0, imageData.Length);
}

// 读取二进制文件
byte[] buffer = new byte[1024];
using (FileStream fs = new FileStream(@"C:\output.jpg", FileMode.Open))
{
    int bytesRead;
    while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
    {
        // 处理读取的数据
    }
}

2. 异步文件操作

.NET 4.0+提供的异步API示例:

public async Task AsyncFileOperation()
{
    string asyncPath = @"C:\Temp\async_demo.txt";
    
    // 异步写入
    await File.WriteAllTextAsync(asyncPath, "异步写入内容");
    
    // 异步读取
    string asyncContent = await File.ReadAllTextAsync(asyncPath);
    Console.WriteLine(asyncContent);
    
    // 使用Stream的异步方法
    using (StreamWriter writer = new StreamWriter(asyncPath, true))
    {
        await writer.WriteLineAsync("追加异步内容");
    }
}

3. 文件监控与事件处理

使用FileSystemWatcher监控目录变化:

var watcher = new FileSystemWatcher(@"C:\Temp")
{
    NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName,
    Filter = "*.txt"
};

watcher.Created += (sender, e) => 
    Console.WriteLine($"文件创建: {e.Name}");
watcher.Changed += (sender, e) => 
    Console.WriteLine($"文件修改: {e.Name}");
watcher.Deleted += (sender, e) => 
    Console.WriteLine($"文件删除: {e.Name}");

watcher.EnableRaisingEvents = true;
Console.WriteLine("监控中...按任意键退出");
Console.ReadKey();

四、目录操作综合示例

完整的目录管理实现:

public class DirectoryManager
{
    public void CreateDirectoryStructure()
    {
        string rootPath = @"C:\DemoDirectory";
        
        // 创建多级目录
        Directory.CreateDirectory(rootPath);
        Directory.CreateDirectory(Path.Combine(rootPath, "SubDir1"));
        Directory.CreateDirectory(Path.Combine(rootPath, "SubDir2"));
        
        // 创建文件
        string filePath = Path.Combine(rootPath, "config.txt");
        File.WriteAllText(filePath, "初始配置内容");
        
        // 复制文件
        string copyPath = Path.Combine(rootPath, "config_backup.txt");
        File.Copy(filePath, copyPath, true);
        
        // 移动文件
        string movePath = Path.Combine(rootPath, "SubDir1", "config.txt");
        File.Move(filePath, movePath);
        
        // 遍历目录
        var files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories);
        Console.WriteLine("目录内容:");
        foreach (var file in files)
        {
            FileInfo fi = new FileInfo(file);
            Console.WriteLine($"{fi.Directory.Name}\\{fi.Name} ({fi.Length} bytes)");
        }
        
        // 删除目录(先清空内容)
        foreach (var dir in Directory.GetDirectories(rootPath))
        {
            Directory.Delete(dir, true);
        }
        Directory.Delete(rootPath);
    }
}

五、异常处理最佳实践

完整的异常处理框架示例:

public class SafeFileOperations
{
    public void WriteFileWithExceptionHandling()
    {
        string filePath = @"C:\Temp\important.dat";
        string data = "关键数据";
        
        try
        {
            // 检查目录是否存在
            string dir = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            
            // 尝试写入文件
            File.WriteAllText(filePath, data);
            Console.WriteLine("文件写入成功");
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine("错误:指定目录不存在且无法创建");
        }
        catch (IOException ex) when ((ex.HResult & 0x0000FFFF) == 0x20)
        {
            Console.WriteLine("错误:文件被其他进程占用");
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("错误:没有足够的权限访问文件");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"未知错误: {ex.Message}");
        }
        finally
        {
            // 清理资源(如果有)
        }
    }
}

六、性能优化建议

1. 大文件处理策略:

  • 使用缓冲流(BufferedStream)减少IO次数
  • 分块读取处理(避免一次性加载大文件)
  • 异步操作避免UI线程阻塞

2. 内存管理技巧:

// 使用using语句确保流正确释放
using (FileStream fs = new FileStream(filePath, FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs, 81920)) // 80KB缓冲区
{
    byte[] buffer = new byte[81920];
    int bytesRead;
    while ((bytesRead = bs.Read(buffer, 0, buffer.Length)) > 0)
    {
        // 处理数据块
    }
}

3. 路径处理规范:

  • 使用Path.Combine()代替字符串拼接
  • 规范化路径(Path.GetFullPath()
  • 跨平台路径处理(使用Path.DirectorySeparatorChar

七、完整项目示例:文件备份工具

using System;
using System.IO;
using System.Linq;

namespace FileBackupTool
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("C#文件备份工具 v1.0");
            Console.WriteLine("====================");
            
            string sourceDir = GetValidPath("请输入源目录路径:");
            string backupDir = GetValidPath("请输入备份目录路径:", createIfNotExists: true);
            
            BackupFiles(sourceDir, backupDir);
            Console.WriteLine("\n备份完成!");
        }

        static string GetValidPath(string prompt, bool createIfNotExists = false)
        {
            while (true)
            {
                Console.Write(prompt);
                string path = Console.ReadLine();
                
                if (!Directory.Exists(path))
                {
                    if (createIfNotExists)
                    {
                        Directory.CreateDirectory(path);
                        Console.WriteLine($"目录 {path} 已创建");
                        break;
                    }
                    Console.WriteLine("目录不存在,请重新输入");
                }
                else
                {
                    break;
                }
            }
            return Path.GetFullPath(Console.ReadLine()); // 修正:应直接返回path
        }

        static void BackupFiles(string source, string backup)
        {
            var files = Directory.GetFiles(source, "*.*", SearchOption.AllDirectories);
            int total = files.Length;
            int processed = 0;
            
            Console.WriteLine($"\n开始备份 {total} 个文件...");
            
            foreach (string file in files)
            {
                try
                {
                    string relativePath = file.Substring(source.Length)
                        .TrimStart(Path.DirectorySeparatorChar);
                    string backupPath = Path.Combine(backup, relativePath);
                    
                    // 确保备份目录存在
                    string backupDir = Path.GetDirectoryName(backupPath);
                    if (!Directory.Exists(backupDir))
                    {
                        Directory.CreateDirectory(backupDir);
                    }
                    
                    // 复制文件
                    File.Copy(file, backupPath, true);
                    processed++;
                    
                    Console.Write($"\r已处理: {processed}/{total}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"\n警告:处理文件时出错 - {ex.Message}");
                }
            }
        }
    }
}
// 修正GetValidPath方法中的逻辑错误
static string GetValidPath(string prompt, bool createIfNotExists = false)
{
    while (true)
    {
        Console.Write(prompt);
        string path = Console.ReadLine();
        
        if (!Directory.Exists(path))
        {
            if (createIfNotExists)
            {
                Directory.CreateDirectory(path);
                Console.WriteLine($"目录 {path} 已创建");
                return path;
            }
            Console.WriteLine("目录不存在,请重新输入");
        }
        else
        {
            return path;
        }
    }
}

关键词

C#文件操作、.NET文件系统、File类、FileInfo类、StreamReader、StreamWriter、异步文件IO、FileSystemWatcher、异常处理、路径处理

简介

本文详细解析C#(.NET)中的文件操作体系,涵盖基础读写、高级二进制处理、异步操作、目录管理及异常处理等核心场景。通过完整代码示例演示文件创建、修改、监控等实用功能,并提供性能优化建议和完整项目实现,适合需要系统掌握.NET文件操作的开发者。