蓝天旭日

高手如云,自己只是个菜鸟而已! 没有人在意你曾经的努力和散漫,只有人关注你是否有成就......
  博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

文件复制管理

Posted on 2008-03-12 16:24  蓝天旭日  阅读(1021)  评论(1编辑  收藏  举报
 

   问题:复制文件夹的时候,只需要覆盖修改过的文件即可,其他同名文件可以直接跳过,但是计算机总是问是否全部覆盖或者全部取消.全部覆盖浪费太多时间,全部取消则达不到我们的要求.

   解决:文件复制管理

1 选择源文件和目标文件

2 碰到同目录同文件时,自动检查最后修改日期,不同则直接覆盖,相同则跳过

3 自动遍历所有子文件夹或者文件

 方法:

  1 建立源文件树(treeview1) 源文件和目标文件树(treeview2)

   2 启动时自动加载系统盘符

   3 单击结点时自动遍历当前结点

   4 点击复制键,自动检查和复制源文件到目标目录,并显示状态.

 运行界面如下:

 详细代码如下:

    using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;

namespace FileOperation

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

           treeView1.Nodes.Add("我的电脑");

           treeView2.Nodes.Add("我的电脑");         

    

        }

        private void EnumDrives(TreeNode ParentNode,TreeView tr)

        {

            if (ParentNode.Nodes.Count == 0)

            {

                DriveInfo[] myAllDrivers = DriveInfo.GetDrives();

                foreach (DriveInfo drive in myAllDrivers)

                {

                    tr.SelectedNode = ParentNode;

                  

                    string type;

                    if (drive.DriveType.ToString() == "Fixed")

                        type = "本地磁盘";

                    else

                        type = "可移动磁盘";

                    TreeNode TempNode = new TreeNode();

                    TempNode.Text = drive.Name + type;//drive.DriveType.ToString();

                    TempNode.Tag = drive.Name;

                    TempNode.ImageIndex = 1;

                    TempNode.SelectedImageIndex = 1;

                    tr.SelectedNode.Nodes.Add(TempNode);

                    tr.SelectedNode.Nodes[tr.SelectedNode.Nodes.Count - 1].EnsureVisible();

                }

            }

        }

        // 递归实现加载目录

        private void EnumDirectories(TreeNode ParentNode,TreeView tr)

        {

           tr.SelectedNode = ParentNode;

            string DirectoryPath;

            try

            {

                 DirectoryPath = ParentNode.Tag.ToString();

            }

            catch

            {

                return;

            }

            if (ParentNode.Nodes.Count == 0)

            {

                if (DirectoryPath.Substring(DirectoryPath.Length - 1) != @"")

                    DirectoryPath += @"";

                try

                {

                    //遍历当前文件夹下的文件夹

                    foreach (string directory in Directory.GetDirectories(DirectoryPath))

                    {

                        TreeNode TempNode = new TreeNode();

                        TempNode.Text = directory.Substring(directory.LastIndexOf(@""") + 1);

                        TempNode.Tag = directory;

                        TempNode.ImageIndex = 3;

                        TempNode.SelectedImageIndex = 4;

                        tr.SelectedNode.Nodes.Add(TempNode);

                        tr.SelectedNode.Nodes[tr.SelectedNode.Nodes.Count - 1].EnsureVisible();

                    }

                    //************************************************编历当前文件夹下的文件

                    if (tr.Name.ToString() == "treeView1")

                    {

                        DirectoryInfo dir = new DirectoryInfo(DirectoryPath);

                        FileInfo[] files = dir.GetFiles();

                        foreach (FileInfo file in files)

                        {

                            TreeNode TempNode = new TreeNode();

                            TempNode.Text = file.Name;

                            TempNode.Tag = file.DirectoryName +"""" +file.Name;

                            TempNode.ImageIndex = 5;

                            TempNode.SelectedImageIndex = 5;

                            tr.SelectedNode.Nodes.Add(TempNode);

                            tr.SelectedNode.Nodes[tr.SelectedNode.Nodes.Count - 1].EnsureVisible();

                        }

                      

                    }

                    //************************************************

                }

                catch (Exception)

                {

                }

                if (tr.Name.ToString() == "treeView1")

                    lb_yuanshi.Text = treeView1.SelectedNode.Tag.ToString();

                else

                    lb_obj.Text = treeView2.SelectedNode.Tag.ToString();

            }

         

        }

     

        private void treeView1_DoubleClick(object sender, EventArgs e)

        {

           // lb_yuanshi.Text = treeView1.SelectedNode.Tag.ToString();

        }

        private void treeView1_MouseClick(object sender, MouseEventArgs e)

        {

         

        }

        ///<summary>

        ///初始化原始目录树

        ///</summary>

        ///<param name="sender"></param>

        ///<param name="e"></param>

        private void treeView1_AfterSelect_1(object sender, TreeViewEventArgs e)

        {

            if (e.Node.Text.ToString() != "我的电脑")

                EnumDirectories(e.Node,treeView1);

            else

            {

                e.Node.ImageIndex = 0; //电脑图标固定

                EnumDrives(e.Node,treeView1);

               

            }

         

        }

        ///<summary>

        ///

        ///</summary>

        ///<param name="sender"></param>

        ///<param name="e"></param>

        private void bt_copy_Click(object sender, EventArgs e)

        {

            this.btInfo.Text = "正在复制文件或者文件夹!请稍候......";

            try

            {

                if (MessageBox.Show("复制" + treeView1.SelectedNode.Tag.ToString() + "    到:    " + treeView2.SelectedNode.Tag.ToString(), "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.OK)

                { 

                    CopyFileFolder(treeView1.SelectedNode.Tag.ToString(), treeView2.SelectedNode.Tag.ToString());

                    this.btInfo.Text = "";

                    treeView2.Nodes.RemoveAt(0);

                    treeView2.Nodes.Add("我的电脑");

                }

            }

            catch

            {

                this.btInfo.Text = "";

                MessageBox.Show("请选择目标目录(文件)和原始目录(文件)");

            }

        }

        ///<summary>

        ///初始化目标目录树

        ///</summary>

        ///<param name="sender"></param>

        ///<param name="e"></param>

        private void treeView2_AfterSelect(object sender, TreeViewEventArgs e)

        {

            if (e.Node.Text.ToString() != "我的电脑")

                EnumDirectories(e.Node, treeView2);

            else

            {

                e.Node.ImageIndex = 0; //电脑图标固定

                EnumDrives(e.Node,treeView2);

              

            }

          

        }

        private void lb_obj_Click(object sender, EventArgs e)

        {

        }

        private void treeView2_Click(object sender, EventArgs e)

        {

         

        }

        ///<summary>

        ///复制文件或者目录

        ///</summary>

        ///<param name="path">原始目录</param>

        ///<param name="objpath">目的目录</param>

        private void CopyFileFolder(string path, string objpath)

        {

            try

            {

                FileInfo fi = new FileInfo(path);

                if (fi.Attributes.ToString().Contains("Directory")) //判断字符串为目录还是文件

                {

                  // MessageBox.Show("目录 ");

                    CopyFolder(path, objpath);

                }

                else

                {

                  // MessageBox.Show("文件 ");

                    //if(File.Exists(@"c:"tempuploads"newFile.txt")) //如果文件存在

                    if (File.Exists(objpath + path.Substring(path.LastIndexOf(@""") + 1)))

                    {

                        FileInfo f1 = new FileInfo(path);

                        FileInfo f2 = new FileInfo(objpath + path.Substring(path.LastIndexOf(@""") + 1));

                        if (f1.LastWriteTime != f2.LastWriteTime||f1.Name!=f2.Name) //文件修改时间一样跳过

                        {

                            File.Copy(@path, objpath + path.Substring(path.LastIndexOf(@""") + 1), true);

                           // MessageBox.Show("检查复制成功");

                        }                    

                    }

                    else

                    {

                        File.Copy(@path, objpath + path.Substring(path.LastIndexOf(@""") + 1),true);

                      // MessageBox.Show("复制成功");

                     

                    }

              

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

        public static void FileCopy(string path, string objpath)

        {

            if (File.Exists(objpath))

            {

                FileInfo f1 = new FileInfo(path);

                FileInfo f2 = new FileInfo(objpath);

                if (f1.LastWriteTime != f2.LastWriteTime) //文件修改时间一样跳过

                {

                   

                    File.Copy(@path, objpath, true);

                   // MessageBox.Show("检查复制成功");

                }

            }

            else

            {

                File.Copy(@path, objpath , true);

               

              // MessageBox.Show("复制成功");

            }

        }

        ///<summary>

        ///创建文件夹

        ///</summary>

        ///<param name="SourcePath">原始路径</param>

        ///<returns></returns>

        public static bool CreateFolder(string SourcePath)

        {

            try

            {

                Directory.CreateDirectory(SourcePath);

                return true;

            }

            catch

            {

                return false;

            }

        }

        ///<summary>

        ///复制文件夹[循环遍历]

        ///</summary>

        ///<param name="SourcePath">原始路径</param>

        ///<param name="DestinPath">目地的路径</param>

        ///<returns></returns>

        public static bool CopyFolder(string SourcePath, string DestinPath)

        {

           

           

            if (Directory.Exists(SourcePath))

            {

                CreateFolder(DestinPath + SourcePath.Substring(SourcePath.LastIndexOf(@""") +1));//第一次创建跟目录文件夹

               

                string sourcePath = SourcePath;//[变化的]原始路径

                string destinPath = DestinPath + SourcePath.Substring(SourcePath.LastIndexOf(@""") + 1);//[变化的]目地的路径

                Queue<string> source = new Queue<string>();//存原始文件夹路径

                Queue<string> destin = new Queue<string>();//存目地的文件夹路径

                bool IsHasChildFolder = true;//是否有子文件夹

                string tempDestinPath = string.Empty;//临时目地的,将被存于destin中

                while (IsHasChildFolder)

                {

                    string[] fileList = Directory.GetFileSystemEntries(sourcePath);// 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组

                    for (int i = 0; i < fileList.Length; i++)// 遍历所有的文件和目录

                    {

                        tempDestinPath = destinPath + """" + Path.GetFileName(fileList[i]);//取得子文件路径

                        if (Directory.Exists(fileList[i]))//存在文件夹时

                        {

                            source.Enqueue(fileList[i]);//当前的子目录的原始路径进队列

                            destin.Enqueue(tempDestinPath);//当前的子目录的目地的路径进队列

                            CreateFolder(tempDestinPath);//创建子文件夹

                        }

                        else//存在文件

                        {

                           

                          // File.Copy(fileList[i], tempDestinPath, true);//复制文件

                            FileCopy(fileList[i], tempDestinPath);

                           

                        }

                    }

                    if (source.Count > 0 && source.Count == destin.Count)//存在子文件夹时

                    {

                        sourcePath = source.Dequeue();

                        destinPath = destin.Dequeue();

                    }

                    else

                    {

                        IsHasChildFolder = false;

                    }

                }

               

                return true;

            }

            else

            {

               

                return false;

            }

        }

    }

}