WinForm(C#)复制文件夹
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace CopyDirectory
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CopyDirectory("c:\\downloads","d:\\");
}
/// <summary>
/// 拷贝文件夹
///By Wang Hw www.pegete.com.cn
/// </summary>
/// <param name="srcdir"></param>
/// <param name="desdir"></param>
private void CopyDirectory(string srcdir, string desdir)
{
string folderName = srcdir.Substring(srcdir.LastIndexOf("\\")+1);
string desfolderdir = desdir +"\\"+ folderName;
if (desdir.LastIndexOf("\\") == (desdir.Length - 1))
{
desfolderdir = desdir + folderName;
}
string[] filenames = Directory.GetFileSystemEntries(srcdir);
foreach (string file in filenames)// 遍历所有的文件和目录
{
if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
{
string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1);
if (!Directory.Exists(currentdir))
{
Directory.CreateDirectory(currentdir);
}
CopyDirectory(file, desfolderdir);
}
else // 否则直接copy文件
{
string srcfileName = file.Substring(file.LastIndexOf("\\")+1);
srcfileName = desfolderdir + "\\" + srcfileName;
if (!Directory.Exists(desfolderdir))
{
Directory.CreateDirectory(desfolderdir);
}
File.Copy(file, srcfileName);
}
}//foreach
}//function end
}
}