[ASP.NET] 不同磁區的目錄移動與複製

今天剛好遇到要將本機目錄移動到遠端目錄上的需求,順便寫了移動目錄的程式,提供給大家參考。

今天剛好遇到要將本機目錄移動到遠端目錄上的需求,順便寫了移動目錄的程式,提供給大家參考。

        /// 
        /// 複製目錄
        /// 
        public static void CopyDirectory(string SourceFolder, string DestinationFolder, bool IsOverWrite = true)
        {
            if (!Directory.Exists(SourceFolder)) return;

            //目標目錄不存在則新建
            if (!Directory.Exists(DestinationFolder))
                Directory.CreateDirectory(DestinationFolder);

            DirectoryInfo srcDir= new DirectoryInfo(SourceFolder);
            
            try
            {
                //先複製目錄下檔案過去
                foreach (FileInfo fi in srcDir.EnumerateFiles())
                    File.Copy(fi.FullName, DestinationFolder + Path.DirectorySeparatorChar + fi.Name, IsOverWrite);
                
                //目錄下的目錄再用遞迴方式複製
                foreach (DirectoryInfo di in srcDir.EnumerateDirectories())
                    CopyDirectory(di.FullName, DestinationFolder + Path.DirectorySeparatorChar + di.Name);
            }
            catch
            {
                throw;
            }
        }
        
        /// 
        /// 移動目錄
        /// 
        public static void MoveDirectory(string SourceFolder, string DestinationFolder, bool IsOverWrite = true)
        {
            CopyDirectory(SourceFolder, DestinationFolder, IsOverWrite);
            Directory.Delete(SourceFolder, true);
        }