C#将文件夹中的文件复制到文件夹目录,并删除文件夹
时间: 2024-11-13 14:40:10 浏览: 44
在C#中,你可以使用`System.IO`命名空间下的`Directory`和`File`类来进行文件和文件夹的操作。首先,你需要遍历源文件夹,然后逐个复制文件到目标文件夹,最后如果需要删除源文件夹,可以使用`Directory.Delete()`方法。以下是一个简单的示例:
```csharp
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// 源文件夹路径
string sourceFolder = @"C:\SourceFolder";
// 目标文件夹路径
string destinationFolder = @"C:\DestinationFolder";
if (!Directory.Exists(destinationFolder))
{
Directory.CreateDirectory(destinationFolder); // 如果目标文件夹不存在,先创建
}
// 遍历源文件夹中的所有文件
foreach (string filePath in Directory.GetFiles(sourceFolder))
{
string fileName = Path.GetFileName(filePath);
string targetPath = Path.Combine(destinationFolder, fileName);
File.Copy(filePath, targetPath, true); // 使用Copy方法复制文件,第三个参数表示是否替换已存在的文件
Console.WriteLine($"Copied file {fileName} to {targetPath}");
}
try
{
// 删除源文件夹,注意这里需要处理异常,因为可能存在其他进程占用导致无法删除的情况
Directory.Delete(sourceFolder, true); // 第二个参数true表示强制删除包括空的子目录
Console.WriteLine("Deleted source folder.");
}
catch (Exception ex)
{
Console.WriteLine($"Failed to delete source folder. Error: {ex.Message}");
}
Console.ReadKey();
}
}
```
阅读全文
相关推荐


















