首页 > 代码库 > C#复制所选目录下所有文件夹和文件
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 PractiseCCode
{
public partial class FrmFolder : Form
{
public FrmFolder()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
//复制所选目录下所有文件夹和文件
string path = this.textBox1.Text.Trim();
string newpath=this.textBox2.Text.Trim();
copydirectory(path, newpath);
MessageBox.Show("ok!");
}
private static void copydirectory(string oldpath, string newpath)
{
DirectoryInfo olddir = new DirectoryInfo(oldpath);
DirectoryInfo newdir = new DirectoryInfo(newpath);
if (!olddir.Exists)
{
MessageBox.Show("选择路径不能为空!");
}
if (!newdir.Exists)
{ //若目标路径没有文件夹,就新建一个
Directory.CreateDirectory(newpath);
}
FileInfo[] files = olddir.GetFiles(); //找出目录下所有文件
foreach (FileInfo fi in files)
{
File.Copy(fi.FullName, newpath + "\\" + fi.Name,true);
}
DirectoryInfo[] dirs = olddir.GetDirectories(); //找出目录下的所有文件夹
foreach ( DirectoryInfo di in dirs)
{
copydirectory(di.FullName, newpath +"\\"+ di.Name);
}
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbdlog = new FolderBrowserDialog();
DialogResult dr = fbdlog.ShowDialog();
if (dr == DialogResult.OK)
{
textBox1.Text = fbdlog.SelectedPath;
}
}
}
}