C# 自訂 XCOPY 類別 :複製資料夾內所有檔案與子資料夾內容到目的資料夾(並覆蓋)




Xopy.class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Tools
{
    public class Xcopy
    {
        private string _message;
        /// <summary>
        /// 錯誤訊息
        /// </summary>
        public string Message
        {
            get { return _message; }
        }

        /// <summary>
        /// 複製檔案群
        /// </summary>
        /// <param name="_source">來源資料夾</param>
        /// <param name="_target">目的資料夾</param>
        /// <param name="recursive">包含子資料夾</param>
        /// <returns>成功 = 1 , 失敗 = -1</returns>
        public int Copy(string _source, string _target, bool recursive = true)
        {
            try
            {
                if (!Directory.Exists(_source))
                {
                    _message = "來源資料夾不存在!";
                    return -1;
                }
                if (!Directory.Exists(_target))
                {
                    // 目的資料夾不存在就建立
                    Directory.CreateDirectory(_target);
                }

                // 先取得來源目露的所有檔案
                string[] files = Directory.GetFiles(_source);
                foreach (var fi in files)
                {
                    string fn = Path.GetFileName(fi);
                    // 複製檔案併覆蓋目的檔案
                    File.Copy(fi, Path.Combine(_target, fn), true);
                }
            }
            catch (Exception e)
            {
                _message = e.Message;
                return -1;
            }

            //繼續處理子目錄
            if (recursive)
            {
                // 取得子目錄
                string[] dirs = Directory.GetDirectories(_source);
                foreach(var di in dirs)
                {
                    string dn = Path.GetFileName(di);
                    // 遞迴呼叫
                    Xcopy x = new Xcopy();
                    if (x.Copy(di, Path.Combine(_target, dn)) == -1)
                    {
                        _message = x.Message;
                        return -1;
                    }
                }
            }

            return 1;
        }
    }
}


使用方式:

包含子資料夾
string sourcePath = "C:\temp";
string targetPath = "D:\temp";
Xcopy x = new Xcopy();
int y = x.Copy(sourcePath, targetPath);
if (y == -1)
{
   console.WriteLine(@"更新檔案到目的資料夾失敗,可能檔案被開啟或是無權限修改:" + x.Message); 
}

不包含子資料夾
string sourcePath = "C:\temp";
string targetPath = "D:\temp";
Xcopy x = new Xcopy();
int y = x.Copy(sourcePath, targetPath, false);
if (y == -1)
{
   console.WriteLine(@"更新檔案到目的資料夾失敗,可能檔案被開啟或是無權限修改:" + x.Message); 
}







留言

Bear表示…
自從有了robocopy,己遺忘了XCOPY
WILDOX寫道…
Bear : xcopy 是我僅有記憶中的東西了

這個網誌中的熱門文章

【研究】列印的條碼為什麼很難刷(掃描)

C# 使用 Process.Start 執行外部程式

統一發票列印小程式