类 | 功能 | 函数 | 举例 |
File | 用于创建、复制、移动、删除和读写文件等操作 | ||
File | 创建文件 | Create | string filePath = "C:\\path\\to\\file.txt"; File.Create(filePath); |
复制文件 | Copy | string sourceFilePath = "C:\\path\\to\\source.txt"; string destFilePath = "C:\\path\\to\\destination.txt"; File.Copy(sourceFilePath, destFilePath); | |
移动文件 | Move | string sourceFilePath = "C:\\path\\to\\source.txt"; string destFilePath = "C:\\path\\to\\destination.txt"; File.Move(sourceFilePath, destFilePath); | |
删除文件 | Delete | string filePath = "C:\\path\\to\\file.txt"; File.Delete(filePath); | |
读取文件内容 | ReadAllText | string filePath = "C:\\path\\to\\file.txt"; string content = File.ReadAllText(filePath); | |
写入文件内容 | WriteAllText | string filePath = "C:\\path\\to\\file.txt"; string content = "Hello, World!"; File.WriteAllText(filePath, content); | |
Directory | Directory类:用于创建、复制、移动和删除文件夹等操作 | ||
Directory | 创建 | CreateDirectory | string path = "C:\\path\\to\\folder"; Directory.CreateDirectory(path); |
删除 | Delete | string path = "C:\\path\\to\\folder"; Directory.Delete(path); | |
移动 | Move | string sourcePath = "C:\\path\\to\\folder"; string destinationPath = "C:\\new\\path\\to\\folder"; Directory.Move(sourcePath, destinationPath); | |
检查 | Exists | string path = "C:\\path\\to\\folder"; bool exists = Directory.Exists(path); | |
获取子文件夹 | GetDirectories | string path = "C:\\parent\\folder"; string[] subDirectories = Directory.GetDirectories(path); foreach (string subDirectory in subDirectories) { Console.WriteLine(subDirectory); } | |
获取子文件 | GetFiles | string path = "C:\\parent\\folder"; string[] files = Directory.GetFiles(path); foreach (string file in files) { Console.WriteLine(file); } | |
拷贝 | Copy | string sourcePath = "C:\\source\\folder"; string destinationPath = "C:\\destination\\folder"; Directory.Copy(sourcePath, destinationPath); | |
Path | Path类是System.IO命名空间中用于处理文件和文件夹路径的常见操作的类。它提供了一组静态方法,可以轻松处理路径字符串。以下是一些Path类常用的方法 | ||
Path | 组合 | Combine | string path1 = "C:\\path\\to"; string path2 = "file.txt"; string combinedPath = Path.Combine(path1, path2); // 结果:C:\path\to\file.txt |
获取文件名 | GetFileName | string path = "C:\\path\\to\\file.txt"; string fileName = Path.GetFileName(path); // 结果:file.txt | |
获取路径 | GetDirectoryName | string path = "C:\\path\\to\\file.txt"; string directoryName = Path.GetDirectoryName(path); // 结果:C:\path\to | |
获取扩展名 | GetExtension | string path = "C:\\path\\to\\file.txt"; string extension = Path.GetExtension(path); // 结果:.txt | |
获取文件名 不含扩展名
|
GetFileName WithoutExtension | string path = "C:\\path\\to\\file.txt"; string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(path); // 结果:file | |
绝对路径 | GetFullPath | string relativePath = "folder\\file.txt"; string fullPath = Path.GetFullPath(relativePath); // 结果:C:\current\directory\folder\file.txt |