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.
In C#, you can useSystem.IO
In the namespaceFile
Class to perform file writing operations.
Example:
- using System;
- using System.IO;
-
- class Program
- {
- static void Main()
- {
- string path = "example.txt";
- string content = "这是一个示例文本。";
-
- // 写入文件
- File.WriteAllText(path, content);
- Console.WriteLine("文件写入成功。");
- }
- }
Similarly, we can also useFile
Class to read file contents:
- 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("文件不存在。");
- }
- }
- }
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.
FileStream
Writing to a file- 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
Reading a file- 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);
- }
- }
- }
In C#, you can useDirectory
Class to create a directory:
- 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("目录已存在。");
- }
- }
- }
can useDirectory
Class to delete a directory:
- 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("目录不存在。");
- }
- }
- }
can useDirectory
The class gets a list of files in a specified directory:
- 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("目录不存在。");
- }
- }
- }
You can use a recursive algorithm to traverse all files in a directory and its subdirectories:
- 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); // 递归遍历子目录
- }
- }
- }
In file system operations, reading and setting file attributes is a common requirement. C# providesFileInfo
class to implement this functionality.
- 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("文件不存在。");
- }
- }
- }
- 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("文件不存在。");
- }
- }
- }
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.
- 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("文件异步写入成功。");
- }
- }
- 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("文件不存在。");
- }
- }
- }
C# providesFileSystemWatcher
Class for monitoring changes to files or directories in a specified directory. This is useful in applications that need to respond to file system changes.
FileSystemWatcher
Watching File Changes- 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}");
- }
- }
I hope this content is helpful to you, thank you for reading!