日期:2014-05-17 浏览次数:20979 次
//**************************************************************************// /* //获得长路径的相对短路径名称 [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer); //实现文件拷贝,递归逐文件拷贝 private void DirectoryCopy(string sourceDir, string targetDir) { if (!Directory.Exists(sourceDir)) { DialogResult OKButtonDown = MessageBox.Show("需要备份的路径不存在,请查看!", "备份失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); if (DialogResult.OK == OKButtonDown) { Application.Exit(); } } string sourceFolderName = sourceDir.Replace(Directory.GetParent(sourceDir).ToString(), "").Replace(Path.DirectorySeparatorChar.ToString(), ""); if (sourceDir == targetDir + sourceFolderName) { DialogResult OKButtonDown = MessageBox.Show("备份的目标路径和原路径相同,不需要备份!", "备份失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); if (DialogResult.OK == OKButtonDown) { Application.Exit(); } } //得到要复制到的路径 string tagetPath = targetDir + Path.DirectorySeparatorChar.ToString() + sourceFolderName; //检查目标路径 if (Directory.Exists(tagetPath)) { DialogResult OKButtonDown = MessageBox.Show("备份的目标路径已经存在,点击是将删除目标并备份,点击否将覆盖并备份", "请查看", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (DialogResult.Yes == OKButtonDown) { Directory.Delete(tagetPath, true); //return; } else if (DialogResult.No == OKButtonDown) { //复制文件 string[] files1 = Directory.GetFiles(sourceDir); for (int i = 0; i < files1.Length; i++) { File.Copy(files1[i], tagetPath + Path.DirectorySeparatorChar.ToString() + Path.GetFileName(files1[i]), true); } //复制目录 string[] dires1 = Directory.GetDirectories(sourceDir); for (int j = 0; j < dires1.Length; j++) { DirectoryCopy(dires1[j], tagetPath); } return; } else if (DialogResult.Cancel == OKButtonDown) { Application.Exit(); } } StringBuilder _shortPath1 = new StringBuilder(255); uint result1 = GetShortPathName(tagetPath, _shortPath1, 255); string MyShortPath1 = _shortPath1.ToString(); if (0 == result1) { Directory.CreateDirectory(tagetPath); } else { Directory.CreateDirectory(MyShortPath1); } //复制文件 string[] files3 = Directory.GetFiles(sourceDir); for (int i = 0; i < files3.Length; i++) { //string longPath = tagetPath + Path.DirectorySeparatorChar.ToString() + Path.GetFileName(files3[i]); //StringBuilder _shortPath = new StringBuilder(255); //uint result = GetShortPathName(longPath, _shortPath, 255); //string MyShortPath = _shortPath.ToString(); File.Copy(files3[i],/*MyShortPath/tagetPath + Path.DirectorySeparatorChar.ToString() + Path.GetFileName(files3[i]), true); } //复制目录 string[] dires3 = Directory.GetDirectories(sourceDir); for (i