내 연락처 정보
우편메소피아@프로톤메일.com
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
파일 시스템 I/O 작업은 모든 프로그래밍 언어의 중요한 부분이며 C#도 예외는 아닙니다. 파일 읽기 및 쓰기, 디렉터리 운영, 파일 스트림 처리 등 C#은 이러한 기능을 구현하기 위한 풍부하고 강력한 클래스 라이브러리를 제공합니다. 이 문서에서는 C#의 파일 시스템 I/O 작업을 자세히 소개하고 코드 예제를 통해 파일과 디렉터리를 효율적으로 처리하는 방법을 보여줍니다.
C#에서는 다음을 사용할 수 있습니다.System.IO
네임스페이스 아래File
파일 쓰기 작업을 수행하는 클래스입니다.
예:
- using System;
- using System.IO;
-
- class Program
- {
- static void Main()
- {
- string path = "example.txt";
- string content = "这是一个示例文本。";
-
- // 写入文件
- File.WriteAllText(path, content);
- Console.WriteLine("文件写入成功。");
- }
- }
마찬가지로, 우리는 또한 사용할 수 있습니다File
파일 내용을 읽는 클래스:
- 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("文件不存在。");
- }
- }
- }
파일 스트림은 파일을 읽고 쓰는 보다 유연한 방법을 제공합니다. 특히 대용량 파일을 처리할 때 파일 스트림은 데이터를 바이트 단위로 읽고 쓸 수 있으므로 과도한 메모리 사용을 방지할 수 있습니다.
FileStream
파일 쓰기- 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
파일 읽기- 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);
- }
- }
- }
C#에서는 다음을 사용할 수 있습니다.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("目录已存在。");
- }
- }
- }
사용할 수 있다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("目录不存在。");
- }
- }
- }
사용할 수 있다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("目录不存在。");
- }
- }
- }
재귀 알고리즘을 사용하여 디렉터리 및 해당 하위 디렉터리의 모든 파일을 탐색할 수 있습니다.
- 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); // 递归遍历子目录
- }
- }
- }
파일 시스템 작업에서는 파일 속성을 읽고 설정하는 것이 일반적인 요구 사항입니다. C#은 다음을 제공합니다.FileInfo
이 기능을 구현하는 클래스입니다.
- 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("文件不存在。");
- }
- }
- }
비동기식 방법을 사용하면 대용량 파일로 작업하거나 시간이 많이 걸리는 파일 작업을 수행할 때 애플리케이션의 응답성을 향상시킬 수 있습니다. C#은 파일을 읽고 쓰는 비동기 메서드를 제공합니다.
- 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#은FileSystemWatcher
지정된 디렉터리의 파일이나 디렉터리에 대한 변경 사항을 모니터링하는 클래스입니다. 이는 파일 시스템 변경에 응답해야 하는 애플리케이션에 유용합니다.
FileSystemWatcher
파일 변경 사항 모니터링- 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}");
- }
- }
이 내용이 여러분에게 도움이 되기를 바랍니다. 읽어주셔서 감사합니다!