欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 文件复制帮助类

程序员文章站 2022-04-27 18:37:28
做下对文件复制操作相关的笔记: /// /// 文件帮助类 /// public class FileHelper { /// /// 复制一个目录下所有文件到一个新目录下 /// ///

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

 

  

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

    }