C# 批量复制文件到新路径并修改文件名
作者:野牛程序员:2023-12-30 17:20:58C#阅读 3116
使用C#进行批量复制文件到新路径并修改文件名可以通过以下代码实现:
using System;
using System.IO;
class Program
{
static void Main()
{
// 源路径
string sourcePath = @"C:\\Path\\To\\Source";
// 目标路径
string destinationPath = @"C:\\Path\\To\\Destination";
// 批量复制并修改文件名
BatchCopyAndRenameFiles(sourcePath, destinationPath, "NewPrefix_");
Console.WriteLine("文件复制完成。");
}
static void BatchCopyAndRenameFiles(string sourcePath, string destinationPath, string newPrefix)
{
// 确保目标路径存在
if (!Directory.Exists(destinationPath))
{
Directory.CreateDirectory(destinationPath);
}
// 获取源路径下的所有文件
string[] files = Directory.GetFiles(sourcePath);
foreach (var filePath in files)
{
// 获取文件名
string fileName = Path.GetFileName(filePath);
// 构造新的文件路径
string newFilePath = Path.Combine(destinationPath, newPrefix + fileName);
// 复制文件
File.Copy(filePath, newFilePath);
Console.WriteLine($"复制文件: {fileName} 到 {newFilePath}");
}
}
}这段代码首先定义了源路径和目标路径,然后调用BatchCopyAndRenameFiles函数来执行批量复制并修改文件名的操作。该函数会检查目标路径是否存在,然后获取源路径下的所有文件,逐一复制到目标路径并修改文件名。在这个例子中,新文件名使用了指定的前缀。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C# 文件和文件夹判断存在与否,并创建
- 下一篇:C# 关于字符串转拼音方法
