在C#中进行Linux文件系统操作时,可以使用.NET Core的System.IO
命名空间中的类和方法。以下是一些常用的文件系统操作示例:
- 创建目录:
using System.IO; string path = "/path/to/directory"; Directory.CreateDirectory(path);
- 创建文件:
using System.IO; string path = "/path/to/file.txt"; File.WriteAllText(path, "Hello, World!");
- 读取文件内容:
using System.IO; string path = "/path/to/file.txt"; string content = File.ReadAllText(path); Console.WriteLine(content);
- 追加文本到文件:
using System.IO; string path = "/path/to/file.txt"; string textToAppend = "\nThis is a new line."; File.AppendAllText(path, textToAppend);
- 删除文件:
using System.IO; string path = "/path/to/file.txt"; File.Delete(path);
- 删除目录及其内容:
using System.IO; string path = "/path/to/directory"; Directory.Delete(path, true);
- 检查文件是否存在:
using System.IO; string path = "/path/to/file.txt"; bool exists = File.Exists(path); Console.WriteLine($"File '{path}' exists: {exists}");
- 获取文件属性(例如,创建时间、大小等):
using System.IO; string path = "/path/to/file.txt"; FileAttributes attributes = File.GetAttributes(path); Console.WriteLine($"Creation time: {attributes.CreationTime}"); Console.WriteLine($"Size: {attributes.Length} bytes");
请注意,这些示例适用于.NET Core和.NET 5及更高版本。在这些版本中,System.IO
命名空间已经跨平台,可以在Linux上运行。如果你使用的是较早的.NET Framework版本,你需要使用System.IO.FileSystem
命名空间中的类,但它们不支持跨平台操作。