C#文件及文件夹重命名
作者:野牛程序员:2023-12-29 17:23:53C#阅读 3218
在C#中,你可以使用System.IO命名空间提供的类来进行文件和文件夹的重命名操作。以下是一个简单的示例代码,用于重命名文件和文件夹:
using System;
using System.IO;
class Program
{
static void Main()
{
// 重命名文件
string oldFilePath = @"C:\\Path\\To\\Your\\File.txt";
string newFilePath = @"C:\\Path\\To\\Your\\NewFileName.txt";
RenameFile(oldFilePath, newFilePath);
// 重命名文件夹
string oldFolderPath = @"C:\\Path\\To\\Your\\Folder";
string newFolderPath = @"C:\\Path\\To\\Your\\NewFolderName";
RenameFolder(oldFolderPath, newFolderPath);
}
static void RenameFile(string oldFilePath, string newFilePath)
{
try
{
File.Move(oldFilePath, newFilePath);
Console.WriteLine("文件重命名成功!");
}
catch (Exception ex)
{
Console.WriteLine($"文件重命名失败:{ex.Message}");
}
}
static void RenameFolder(string oldFolderPath, string newFolderPath)
{
try
{
Directory.Move(oldFolderPath, newFolderPath);
Console.WriteLine("文件夹重命名成功!");
}
catch (Exception ex)
{
Console.WriteLine($"文件夹重命名失败:{ex.Message}");
}
}
}请注意,这里的代码中使用了File.Move来重命名文件,使用Directory.Move来重命名文件夹。确保在执行这些操作之前,目标文件或文件夹是不存在的,否则会引发异常。在实际应用中,请根据需要添加适当的错误处理和边界检查。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C# 修改项目文件夹名称
- 下一篇:c#定期删除文件的方法
