기술나눔

C#의 파일 시스템 I/O 작업에 대한 심층적인 이해

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

파일 시스템 I/O 작업은 모든 프로그래밍 언어의 중요한 부분이며 C#도 예외는 아닙니다. 파일 읽기 및 쓰기, 디렉터리 운영, 파일 스트림 처리 등 C#은 이러한 기능을 구현하기 위한 풍부하고 강력한 클래스 라이브러리를 제공합니다. 이 문서에서는 C#의 파일 시스템 I/O 작업을 자세히 소개하고 코드 예제를 통해 파일과 디렉터리를 효율적으로 처리하는 방법을 보여줍니다.

1. 파일 읽기 및 쓰기
파일 쓰기

C#에서는 다음을 사용할 수 있습니다.System.IO네임스페이스 아래File파일 쓰기 작업을 수행하는 클래스입니다.

예:

  1. using System;
  2. using System.IO;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. string path = "example.txt";
  8. string content = "这是一个示例文本。";
  9. // 写入文件
  10. File.WriteAllText(path, content);
  11. Console.WriteLine("文件写入成功。");
  12. }
  13. }
파일 읽기

마찬가지로, 우리는 또한 사용할 수 있습니다File파일 내용을 읽는 클래스:

  1. using System;
  2. using System.IO;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. string path = "example.txt";
  8. if (File.Exists(path))
  9. {
  10. // 读取文件内容
  11. string content = File.ReadAllText(path);
  12. Console.WriteLine("文件内容:");
  13. Console.WriteLine(content);
  14. }
  15. else
  16. {
  17. Console.WriteLine("文件不存在。");
  18. }
  19. }
  20. }
2. 파일 스트림 사용

파일 스트림은 파일을 읽고 쓰는 보다 유연한 방법을 제공합니다. 특히 대용량 파일을 처리할 때 파일 스트림은 데이터를 바이트 단위로 읽고 쓸 수 있으므로 과도한 메모리 사용을 방지할 수 있습니다.

사용FileStream파일 쓰기
  1. using System;
  2. using System.IO;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. string path = "filestream_example.txt";
  8. byte[] data = System.Text.Encoding.UTF8.GetBytes("通过FileStream写入的数据。");
  9. using (FileStream fs = new FileStream(path, FileMode.Create))
  10. {
  11. fs.Write(data, 0, data.Length);
  12. Console.WriteLine("数据已通过FileStream写入。");
  13. }
  14. }
  15. }
사용FileStream파일 읽기
  1. using System;
  2. using System.IO;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. string path = "filestream_example.txt";
  8. using (FileStream fs = new FileStream(path, FileMode.Open))
  9. {
  10. byte[] data = new byte[fs.Length];
  11. fs.Read(data, 0, data.Length);
  12. string content = System.Text.Encoding.UTF8.GetString(data);
  13. Console.WriteLine("通过FileStream读取的内容:");
  14. Console.WriteLine(content);
  15. }
  16. }
  17. }
3. 작업 디렉토리
디렉터리 생성

C#에서는 다음을 사용할 수 있습니다.Directory디렉토리를 생성하는 클래스:

  1. using System;
  2. using System.IO;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. string dirPath = "example_directory";
  8. if (!Directory.Exists(dirPath))
  9. {
  10. Directory.CreateDirectory(dirPath);
  11. Console.WriteLine("目录创建成功。");
  12. }
  13. else
  14. {
  15. Console.WriteLine("目录已存在。");
  16. }
  17. }
  18. }
디렉토리 삭제

사용할 수 있다Directory디렉토리를 삭제하는 클래스:

  1. using System;
  2. using System.IO;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. string dirPath = "example_directory";
  8. if (Directory.Exists(dirPath))
  9. {
  10. Directory.Delete(dirPath, true);
  11. Console.WriteLine("目录已删除。");
  12. }
  13. else
  14. {
  15. Console.WriteLine("目录不存在。");
  16. }
  17. }
  18. }
4. 파일 및 디렉터리 탐색
디렉터리에 있는 파일 목록 가져오기

사용할 수 있다Directory클래스는 지정된 디렉터리의 파일 목록을 가져옵니다.

  1. using System;
  2. using System.IO;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. string dirPath = "example_directory";
  8. if (Directory.Exists(dirPath))
  9. {
  10. string[] files = Directory.GetFiles(dirPath);
  11. Console.WriteLine("目录中的文件:");
  12. foreach (string file in files)
  13. {
  14. Console.WriteLine(file);
  15. }
  16. }
  17. else
  18. {
  19. Console.WriteLine("目录不存在。");
  20. }
  21. }
  22. }
재귀적으로 디렉터리를 탐색합니다.

재귀 알고리즘을 사용하여 디렉터리 및 해당 하위 디렉터리의 모든 파일을 탐색할 수 있습니다.

  1. using System;
  2. using System.IO;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. string dirPath = "example_directory";
  8. if (Directory.Exists(dirPath))
  9. {
  10. TraverseDirectory(dirPath);
  11. }
  12. else
  13. {
  14. Console.WriteLine("目录不存在。");
  15. }
  16. }
  17. static void TraverseDirectory(string dirPath)
  18. {
  19. string[] files = Directory.GetFiles(dirPath);
  20. string[] directories = Directory.GetDirectories(dirPath);
  21. foreach (string file in files)
  22. {
  23. Console.WriteLine("文件: " + file);
  24. }
  25. foreach (string directory in directories)
  26. {
  27. Console.WriteLine("目录: " + directory);
  28. TraverseDirectory(directory); // 递归遍历子目录
  29. }
  30. }
  31. }
5. 파일 속성 작업

파일 시스템 작업에서는 파일 속성을 읽고 설정하는 것이 일반적인 요구 사항입니다. C#은 다음을 제공합니다.FileInfo이 기능을 구현하는 클래스입니다.

파일 속성 읽기
  1. using System;
  2. using System.IO;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. string filePath = "example.txt";
  8. FileInfo fileInfo = new FileInfo(filePath);
  9. if (fileInfo.Exists)
  10. {
  11. Console.WriteLine("文件名: " + fileInfo.Name);
  12. Console.WriteLine("文件路径: " + fileInfo.FullName);
  13. Console.WriteLine("文件大小: " + fileInfo.Length);
  14. Console.WriteLine("创建时间: " + fileInfo.CreationTime);
  15. Console.WriteLine("最后访问时间: " + fileInfo.LastAccessTime);
  16. Console.WriteLine("最后修改时间: " + fileInfo.LastWriteTime);
  17. }
  18. else
  19. {
  20. Console.WriteLine("文件不存在。");
  21. }
  22. }
  23. }
파일 속성 설정
  1. using System;
  2. using System.IO;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. string filePath = "example.txt";
  8. FileInfo fileInfo = new FileInfo(filePath);
  9. if (fileInfo.Exists)
  10. {
  11. // 设置文件属性
  12. fileInfo.Attributes = FileAttributes.ReadOnly;
  13. Console.WriteLine("文件属性已设置为只读。");
  14. // 恢复文件属性
  15. fileInfo.Attributes = FileAttributes.Normal;
  16. Console.WriteLine("文件属性已恢复为正常。");
  17. }
  18. else
  19. {
  20. Console.WriteLine("文件不存在。");
  21. }
  22. }
  23. }
6. 비동기 파일 I/O 작업

비동기식 방법을 사용하면 대용량 파일로 작업하거나 시간이 많이 걸리는 파일 작업을 수행할 때 애플리케이션의 응답성을 향상시킬 수 있습니다. C#은 파일을 읽고 쓰는 비동기 메서드를 제공합니다.

비동기식으로 파일 쓰기
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. class Program
  5. {
  6. static async Task Main()
  7. {
  8. string path = "async_example.txt";
  9. string content = "这是一个异步写入示例。";
  10. await File.WriteAllTextAsync(path, content);
  11. Console.WriteLine("文件异步写入成功。");
  12. }
  13. }
비동기적으로 파일 읽기
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. class Program
  5. {
  6. static async Task Main()
  7. {
  8. string path = "async_example.txt";
  9. if (File.Exists(path))
  10. {
  11. string content = await File.ReadAllTextAsync(path);
  12. Console.WriteLine("文件内容:");
  13. Console.WriteLine(content);
  14. }
  15. else
  16. {
  17. Console.WriteLine("文件不存在。");
  18. }
  19. }
  20. }
7. 파일 모니터링

C#은FileSystemWatcher 지정된 디렉터리의 파일이나 디렉터리에 대한 변경 사항을 모니터링하는 클래스입니다. 이는 파일 시스템 변경에 응답해야 하는 애플리케이션에 유용합니다.

사용FileSystemWatcher파일 변경 사항 모니터링
  1. using System;
  2. using System.IO;
  3. class Program
  4. {
  5. static void Main()
  6. {
  7. string path = "example_directory";
  8. if (!Directory.Exists(path))
  9. {
  10. Directory.CreateDirectory(path);
  11. }
  12. FileSystemWatcher watcher = new FileSystemWatcher();
  13. watcher.Path = path;
  14. watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size;
  15. watcher.Filter = "*.*";
  16. watcher.Changed += OnChanged;
  17. watcher.Created += OnChanged;
  18. watcher.Deleted += OnChanged;
  19. watcher.Renamed += OnRenamed;
  20. watcher.EnableRaisingEvents = true;
  21. Console.WriteLine("正在监视目录: " + path);
  22. Console.WriteLine("按任意键退出...");
  23. Console.ReadKey();
  24. }
  25. private static void OnChanged(object source, FileSystemEventArgs e)
  26. {
  27. Console.WriteLine($"文件: {e.FullPath} {e.ChangeType}");
  28. }
  29. private static void OnRenamed(object source, RenamedEventArgs e)
  30. {
  31. Console.WriteLine($"文件: {e.OldFullPath} 重命名为 {e.FullPath}");
  32. }
  33. }

이 내용이 여러분에게 도움이 되기를 바랍니다. 읽어주셔서 감사합니다!