| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
- namespace HXX.Scanner.Copier
- {
- /// <summary>
- /// 目录拷贝
- /// </summary>
- class DirCopy
- {
- /// <summary>
- /// 检测源目录是否存在,如果存在则创建对应目标目录
- /// </summary>
- /// <param name="fml_sDst">目标目录</param>
- /// <param name="fml_sSrc">源目录</param>
- /// <returns></returns>
- public static bool CheckDirs(string fml_sDst, string fml_sSrc)
- {
- bool ok1, ok2, ok3;
- ok1 = Directory.Exists(fml_sDst);
- ok2 = Directory.Exists(fml_sSrc);
- if (!ok2)
- {
- LogManager.WriteLog("升级覆盖--源目录不存在" + Environment.NewLine + fml_sSrc);
- return false;
- }
- // 目标目录不存在则进行创建
- if (!ok1)
- {
- try
- {
- Directory.CreateDirectory(fml_sDst);
- ok3 = true;
- return true;
- }
- catch (Exception ex)
- {
- ok3 = false;
- LogManager.WriteLog("升级覆盖--创建目标目录失败" + Environment.NewLine + fml_sDst);
- return false;
- }
- }
- else
- {
- return true;
- }
- }
- /// <summary>
- /// 文件夹拷贝
- /// 从指定的源目录拷贝所有文件到目标目录
- /// 如果目标文件存在则跳过拷贝
- /// </summary>
- /// <param name="fml_sDst">目标目录</param>
- /// <param name="fml_sSrc">源目录</param>
- /// <returns></returns>
- public static bool Copy(string fml_sDst, string fml_sSrc)
- {
- if (!CheckDirs(fml_sDst, fml_sSrc))
- {
- return false;
- }
- /* 迭代拷贝文件
- * 1.将源目录存入列表
- * 2.检测当前列表第一项目录是否存在,不存在则创建
- * 3.检测当前列表第一项目录下的所有文件,并拷贝到目标文件夹下
- * 4.检测当前列表第一项目录下的文件夹,添加到列表
- * 5.移除第一项
- * 6.循环第2到第4步,直到列表项为0 */
- List<string> dirs = new List<string>();
- dirs.Add(fml_sSrc);
- while (dirs.Count != 0)
- {
- string dst_dir = dirs[0].Replace(fml_sSrc, fml_sDst);
- // 如果目标目录不存在则创建
- if (!Directory.Exists(dst_dir))
- {
- Directory.CreateDirectory(dst_dir);
- }
- List<string> fnames = new List<string>(Directory.EnumerateFiles(dirs[0]));
- foreach (string fname in fnames)
- {
- FileInfo fi = new FileInfo(fname); //获取文件信息
- string dst_name = dst_dir + @"\" + fi.Name;
- try
- {
- // 检测本地是否已经存在该文件,如果存在则跳过
- if (!File.Exists(dst_name))
- {
- File.Copy(fname, dst_name);
- }
- else
- {
- Console.WriteLine("文件 {0} 已存在,跳过拷贝。", dst_name);
- }
- }
- catch (Exception ex)
- {
- LogManager.WriteLog("升级覆盖--拷贝文件错误");
- }
- }
- // 列举当前目录下的子目录列表
- List<string> sub_dirs = new List<string>(Directory.EnumerateDirectories(dirs[0]));
- dirs.AddRange(sub_dirs);
- dirs.RemoveAt(0);
- }
- return true;
- }
- /// <summary>
- /// 预留 在独立线程内进行拷贝
- /// </summary>
- /// <param name="fml_sDst"></param>
- /// <param name="fml_sSrc"></param>
- /// <returns></returns>
- public static bool threadCopy(string fml_sDst, string fml_sSrc)
- {
- return false;
- }
- }
- }
|