You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何复制指定文件到目标目录并自动创建指定子目录?

解决方案:复制文件并保留指定子目录结构

我来帮你搞定这个文件复制的问题!核心思路是提取源文件中需要保留的相对路径部分,然后在目标目录下重建这个路径,最后完成文件复制。下面是具体的实现代码和说明:

步骤说明

  • 先定义源文件的根目录(即Patches文件夹)和目标根目录(即Builds文件夹)
  • 对每个源文件,计算它相对于源根目录的路径(这部分就是你需要保留的0.0.0.2\SomeDir\OtherDir结构)
  • 在目标根目录下创建对应的子目录
  • 复制文件到目标路径

C# 代码实现

using System.IO;

// 定义源根和目标根目录
string sourceRoot = @"C:\Users\Machina\Documents\Visual Studio 2017\Projects\P\Patcher\bin\Debug\Patches";
string targetRoot = @"C:\Users\Machina\Documents\Visual Studio 2017\Projects\P\Patcher\bin\Debug\Builds";

// 遍历你的文件列表(假设fileList是存储源文件路径的集合)
foreach (string sourceFilePath in fileList)
{
    // 获取源文件相对于源根的相对路径(比如"0.0.0.2\SomeDir\OtherDir\File.txt")
    string relativePath = Path.GetRelativePath(sourceRoot, sourceFilePath);
    
    // 拼接目标文件的完整路径
    string targetFilePath = Path.Combine(targetRoot, relativePath);
    
    // 提取目标文件所在的目录,确保目录存在(不存在则自动创建)
    string targetDirectory = Path.GetDirectoryName(targetFilePath);
    Directory.CreateDirectory(targetDirectory);
    
    // 执行文件复制,第二个参数为true表示覆盖已存在的同名文件
    File.Copy(sourceFilePath, targetFilePath, true);
}

兼容旧版.NET Framework的处理

如果你的项目使用的是.NET Framework 4.7及以下版本,Path.GetRelativePath方法不可用,可以用以下方式计算相对路径:

// 替代Path.GetRelativePath的兼容写法
Uri sourceRootUri = new Uri(sourceRoot + Path.DirectorySeparatorChar);
Uri sourceFileUri = new Uri(sourceFilePath);
string relativePath = sourceRootUri.MakeRelativeUri(sourceFileUri).ToString().Replace('/', '\\');

这段代码会自动帮你在Builds目录下创建0.0.0.2\SomeDir\OtherDir子目录,并将File.txt复制到该路径下,完全符合你的需求。

内容的提问来源于stack exchange,提问作者Piotr Bibinin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:10:00