深入学习ing

C# 文件复制帮助类

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

 

  

/// <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);
                }
            }
        }

    }

 

posted on 2020-03-31 16:39  深入学习ing  阅读(...)  评论(...编辑  收藏

导航

统计