2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Dateisystem-E/A-Operationen sind ein wichtiger Bestandteil jeder Programmiersprache, und C# bildet da keine Ausnahme. Ob es darum geht, Dateien zu lesen und zu schreiben, Verzeichnisse zu betreiben oder Dateiströme zu verarbeiten, C# bietet eine umfangreiche und leistungsstarke Klassenbibliothek zur Implementierung dieser Funktionen. In diesem Artikel werden Dateisystem-E/A-Vorgänge in C# ausführlich vorgestellt und anhand von Codebeispielen gezeigt, wie Dateien und Verzeichnisse effizient verarbeitet werden.
In C# können Sie verwendenSystem.IO
unter NamensraumFile
Klasse zum Ausführen von Dateischreibvorgängen.
Beispiel:
- using System;
- using System.IO;
-
- class Program
- {
- static void Main()
- {
- string path = "example.txt";
- string content = "这是一个示例文本。";
-
- // 写入文件
- File.WriteAllText(path, content);
- Console.WriteLine("文件写入成功。");
- }
- }
Ebenso können wir auch verwendenFile
Klasse zum Lesen von Dateiinhalten:
- 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("文件不存在。");
- }
- }
- }
Dateistreams bieten eine flexiblere Möglichkeit, Dateien zu lesen und zu schreiben. Insbesondere bei der Verarbeitung großer Dateien können Dateistreams Daten Byte für Byte lesen und schreiben und so eine übermäßige Speichernutzung vermeiden.
FileStream
Datei schreiben- 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
Datei lesen- 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# können Sie verwendenDirectory
Klasse zum Erstellen eines Verzeichnisses:
- 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("目录已存在。");
- }
- }
- }
Kann benutzenDirectory
Klasse zum Löschen eines Verzeichnisses:
- 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("目录不存在。");
- }
- }
- }
Kann benutzenDirectory
Die Klasse ruft die Liste der Dateien im angegebenen Verzeichnis ab:
- 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("目录不存在。");
- }
- }
- }
Sie können einen rekursiven Algorithmus verwenden, um alle Dateien in einem Verzeichnis und seinen Unterverzeichnissen zu durchlaufen:
- 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); // 递归遍历子目录
- }
- }
- }
Bei Dateisystemoperationen ist das Lesen und Festlegen von Dateiattributen eine häufige Anforderung. C# bietetFileInfo
Klasse, um diese Funktionalität zu implementieren.
- 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("文件不存在。");
- }
- }
- }
Die Verwendung asynchroner Methoden kann die Reaktionsfähigkeit Ihrer Anwendung verbessern, wenn Sie mit großen Dateien arbeiten oder zeitaufwändige Dateivorgänge ausführen. C# bietet asynchrone Methoden zum Lesen und Schreiben von Dateien.
- 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# bietetFileSystemWatcher
Klasse zum Überwachen von Änderungen an Dateien oder Verzeichnissen in einem angegebenen Verzeichnis. Dies ist nützlich bei Anwendungen, die auf Dateisystemänderungen reagieren müssen.
FileSystemWatcher
Überwachen Sie Dateiänderungen- 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}");
- }
- }
Ich hoffe, dieser Inhalt ist hilfreich für Sie, danke fürs Lesen!