Technology Sharing

In-depth understanding of file system I/O operations in C#

2024-07-12

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

File system I/O operations are an important part of any programming language, and C# is no exception. Whether it is reading and writing files, operating directories, or processing file streams, C# provides a rich and powerful class library to implement these functions. This article will introduce file system I/O operations in C# in detail, and show how to efficiently process files and directories through code examples.

1. Read and write files
Writing to a file

In C#, you can useSystem.IOIn the namespaceFileClass to perform file writing operations.

Example:

  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. }
Reading a file

Similarly, we can also useFileClass to read file contents:

  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. Using file streams

File streams provide a more flexible way to read and write files, especially when processing large files. File streams can read and write data byte by byte, thus avoiding excessive memory usage.

useFileStreamWriting to a file
  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. }
useFileStreamReading a file
  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. Operation Directory
Create a directory

In C#, you can useDirectoryClass to create a 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. }
Deleting a Directory

can useDirectoryClass to delete a 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. Traversing files and directories
Get a list of files in a directory

can useDirectoryThe class gets a list of files in a specified 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. }
Recursive directory traversal

You can use a recursive algorithm to traverse all files in a directory and its subdirectories:

  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. File attribute operations

In file system operations, reading and setting file attributes is a common requirement. C# providesFileInfoclass to implement this functionality.

Reading file attributes
  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. }
Setting file attributes
  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. Asynchronous file I/O operations

When processing large files or performing time-consuming file operations, using asynchronous methods can improve the responsiveness of the application. C# provides asynchronous methods to read and write files.

Writing files asynchronously
  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. }
Reading files asynchronously
  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. File Monitoring

C# providesFileSystemWatcherClass for monitoring changes to files or directories in a specified directory. This is useful in applications that need to respond to file system changes.

useFileSystemWatcherWatching File Changes
  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. }

I hope this content is helpful to you, thank you for reading!