转移文件夹及其里面所有内容

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/// <summary>
/// 移动图片文件夹,从原来的wwwroot/graphics文件夹转移到Picture文件夹
///转移完毕删除原来的graphics文件夹
/// </summary>
public void MoveGraphicsFolder()
{
    try
    {
        // 定义源文件夹路径
        string sourcePath = Path.Combine("wwwroot", "graphics");
        // 定义目标文件夹路径
        string targetPath = "Picture";
 
        // 如果目标文件夹已存在,则删除它
        string destinationGraphicsPath = Path.Combine(targetPath, "graphics");
        if (!Directory.Exists(destinationGraphicsPath))
        {
            Directory.CreateDirectory(destinationGraphicsPath);
        }
 
        // 确保目标目录存在,如果不存在则创建
        if (!Directory.Exists(targetPath))
        {
            Directory.CreateDirectory(targetPath);
        }
 
        // 获取源目录和目标目录中的所有文件
        string[] sourceFiles = Directory.GetFiles(sourcePath, "*", SearchOption.AllDirectories);
        string[] targetFiles = Directory.GetFiles(destinationGraphicsPath, "*", SearchOption.AllDirectories);
 
 
 
        // 创建目标目录中不存在的目录
        foreach (string sourceFile in sourceFiles)
        {
            string relativePath = Path.GetRelativePath(sourcePath, sourceFile);
            string targetFile = Path.Combine(destinationGraphicsPath, relativePath);
 
            string targetDirectory = Path.GetDirectoryName(targetFile)!;
            if (!Directory.Exists(targetDirectory))
            {
                Directory.CreateDirectory(targetDirectory);
            }
        }
 
        // 处理每一个文件
        foreach (string sourceFile in sourceFiles)
        {
            string relativePath = Path.GetRelativePath(sourcePath, sourceFile);
            string targetFile = Path.Combine(destinationGraphicsPath, relativePath);
 
            // 如果目标目录中已存在相同路径的文件,则进行覆盖
            if (Array.Exists(targetFiles, f => string.Equals(f, targetFile, StringComparison.OrdinalIgnoreCase)))
            {
                File.Copy(sourceFile, targetFile, true);
            }
            // 如果目标目录中不存在相同路径的文件,则进行复制
            else
            {
                File.Move(sourceFile, targetFile);
            }
        }
 
        // 删除源目录
        Directory.Delete(sourcePath, true);
    }
    catch (Exception)
    {
        throw;
    }
}

  

 

posted @   ProZkb  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界
历史上的今天:
2019-06-01 sql中表变量
点击右上角即可分享
微信分享提示