具有不同子文件夹的文件夹,我想将所有子文件夹从源文件夹复制到目标文件夹

时间:2014-01-11 11:35:44

标签: c# .net

我在D:/ myprojects / payrole

中有项目文档

在这些“payrole”中,我有不同的文件和不同的子文件夹

我需要将文件和子文件夹复制到E:/ myprojects / payrole

将文件和子文件夹从D盘复制到E盘

如何使用c#在Windows应用程序中执行这些过程? 请给我一些想法

1 个答案:

答案 0 :(得分:0)

private void Form1_Load(object sender, EventArgs e)

{
      CopyFolder(@"C:\Text", @"D:\Sites");

}

    static public void CopyFolder(string sourceFolder, string desFolder)
    {
        try
        {
           // files from sourcefolder
            string[] files = System.IO.Directory.GetFiles(sourceFolder);

    // subfolder from sourcefolder
            string[] folders = Directory.GetDirectories(sourceFolder);


            foreach (string file in files)
            {
                string name = Path.GetFileName(file);
                string dest = Path.Combine(desFolder, name);
                File.Copy(file, dest);
            }

            foreach (string folder in folders)
            {
                string name = Path.GetFileName(folder);
                string dest = Path.Combine(desFolder, name);

                if (!Directory.Exists(dest))
                    Directory.CreateDirectory(dest);

                string[] subfiles = System.IO.Directory.GetFiles(folder);
                foreach (string subfile in subfiles)
                {
                    string subname = Path.GetFileName(subfile);
                    string subdest = Path.Combine(dest, subname);
                    File.Copy(subfile, subdest);
                }
            }
        }
        catch (Exception e)
        {

            MessageBox.Show(e.Message.ToString());
        }