C# 复制文件和文件夹
因为有好多台服务器,每次都要手动进行备份,有点麻烦,而且容易出错,所以写了下面这个用程序来备份,比较简单,就是用C#复制文件和文件
using System;using System.Collections.Generic;using System.Text;using System.IO;using System.Configuration;namespace Copy{ class Program { static void Main(string[] args) { //eg D:\publish //不用 ConfigurationManager而用下面这个是因为 FrameWork2.0 string sourceDir = ConfigurationSettings.AppSettings["SourcePath"].ToString(); //eg D:\BackUp string targetDir = ConfigurationSettings.AppSettings["TargetPath"].ToString(); Console.WriteLine("正在进行备份,请不要关闭窗口............."); DirectoryCopy(sourceDir, targetDir); Console.WriteLine("成功复制备份,按任意键关闭窗口............"); Console.ReadKey(); } static void DirectoryCopy(string sourceDir, string targetDir) { if (!Directory.Exists(sourceDir)) return; if (!Directory.Exists(targetDir)) return; string sourceFolderName = sourceDir.Replace(Directory.GetParent(sourceDir).ToString(), "").Replace(Path.DirectorySeparatorChar.ToString(), ""); if (sourceDir == targetDir + sourceFolderName) return; //要复制到的路径 string tagetPath=targetDir + Path.DirectorySeparatorChar.ToString() + sourceFolderName; if (Directory.Exists(tagetPath)) { Directory.Delete(tagetPath, true); } Directory.CreateDirectory(tagetPath); //复制文件 string[] files = Directory.GetFiles(sourceDir); for (int i = 0; i < files.Length; i++) { File.Copy(files[i], tagetPath+Path.DirectorySeparatorChar.ToString()+Path.GetFileName(files[i])); } //复制目录 string[] dires = Directory.GetDirectories(sourceDir); for (int j = 0; j < dires.Length; j++) { DirectoryCopy(dires[j], tagetPath); } } }}
TAG: