C# 文件复制帮助类

最后都变了- 提交于 2020-03-31 17:58:31

  做下对文件复制操作相关的笔记:

 

  

/// <summary>
    /// 文件帮助类
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        /// 复制一个目录下所有文件到一个新目录下
        /// </summary>
        /// <param name="copyPath">原目录</param>
        /// <param name="newFilePathFunc">新目录生成方法</param>
        /// <param name="isCopySubFolder">是否复制子文件夹内的文件</param>
        /// <param name="isOverwrite">可选:是否覆盖(默认覆盖)</param>
        public static void CopyFileList(string copyPath, Func<string, string> newFilePathFunc, bool isCopySubFolder = true, bool isOverwrite = true)
        {
            //复制当前目录下所有文件到新目录中
            List<string> fileList = Directory.GetFiles(copyPath).ToList();

            foreach (var filePath in fileList)
            {
                string newFilePath = newFilePathFunc(filePath);
                string newFileDirectory = newFilePath.Substring(0, newFilePath.LastIndexOf('\\') + 1);
                if (!Directory.Exists(newFileDirectory))
                {
                    Directory.CreateDirectory(newFileDirectory);
                }

                if (isOverwrite || !File.Exists(newFilePath))
                {
                    File.Copy(filePath, newFilePath, isOverwrite);
                }

            }

            //复制子目录下所有文件到新目录中
            if (isCopySubFolder)
            {
                List<string> subFolderList = Directory.GetDirectories(copyPath).ToList();
                foreach (var subFolder in subFolderList)
                {
                    FileHelper.CopyFileList(subFolder, newFilePathFunc, isCopySubFolder, isOverwrite);
                }
            }

        }

        /// <summary>
        /// 复制一组文件到一个新目录下
        /// </summary>
        /// <param name="filePathList">文件列表</param>
        /// <param name="newFilePathFunc">新目录生成方法</param>
        /// <param name="isOverwrite">可选:是否覆盖(默认覆盖)</param>
        public static void CopyFileList(List<string> filePathList, Func<string, string> newFilePathFunc, bool isOverwrite = true)
        {
            //将上月保存未改变多币种数据复制到本月中(本月已存在多币种数据不覆盖)
            foreach (var filePath in filePathList)
            {
                string newFilePath = newFilePathFunc(filePath);
                string newFileDirectory = newFilePath.Substring(0, newFilePath.LastIndexOf('\\') + 1);
                if (!Directory.Exists(newFileDirectory))
                {
                    Directory.CreateDirectory(newFileDirectory);
                }

                if (isOverwrite || !File.Exists(newFilePath))
                {
                    File.Copy(filePath, newFilePath, isOverwrite);
                }
            }
        }

    }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!