C# 文件/文件夹处理常用类 File,Directory,Path

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值