码迷,mamicode.com
首页 > Windows程序 > 详细

Winform文件夹内容同步更新、备份、日志、恢复

时间:2014-07-06 10:30:48      阅读:371      评论:0      收藏:0      [点我收藏+]

标签:c#   备份   

相信大家做项目或者处理文件时候经常要用到备份的功能,这里给大家做一个可以同步更新文件夹内容并且备份的Winform程序,目前地址路径在App.Config文件里面设置,如需更改直接用记事本编辑即可,下面放代码和截图。

1.CS代码:

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;
using System.Configuration;
using System.Text.RegularExpressions;

namespace Update
{
    public partial class AutoUpdate : Form
    {
        string filePath = ConfigurationManager.AppSettings["FilePath"].ToString();
        string targetPath = ConfigurationManager.AppSettings["TargetPath"].ToString();
        string Timing = ConfigurationManager.AppSettings["Timing"].ToString();
        string backPath = ConfigurationManager.AppSettings["backUpPath"].ToString();
        int count = 0;

        string fullPath = "D:/backup/backup.txt";//设置日志地址

        public AutoUpdate()
        {
            InitializeComponent();

            this.txtFile.Text = filePath;
            this.txtTo.Text = targetPath;
            this.txtTime.Text = Timing;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            //更新同时调用备份
            backup();

            if (filePath != "")
            {
                if (CopyDir(filePath, targetPath))
                {
                    MessageBox.Show("更新成功!!!");
                }
                else
                {
                    MessageBox.Show("更新失败!!!");
                }
            }
            else
            {
                MessageBox.Show("请正确设置源地址!");
            }
        }

        /// <summary>
        /// 更新文件处理
        /// </summary>
        /// <param name="srcPath"></param>
        /// <param name="aimPath"></param>
        /// <returns></returns>
        private bool CopyDir(string srcPath, string aimPath)
        {
            bool copyFile = false;
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加 
                if (aimPath[aimPath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
                {
                    aimPath += System.IO.Path.DirectorySeparatorChar;
                }
                // 判断目标目录是否存在如果不存在则新建 
                if (!System.IO.Directory.Exists(aimPath))
                {
                    System.IO.Directory.CreateDirectory(aimPath);
                }
                // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组 
                // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法 
                // string[] fileList = Directory.GetFiles(srcPath); 
                string[] fileList = System.IO.Directory.GetFileSystemEntries(srcPath);
                string str = "";
                if (count == 0)
                {
                    str = DateTime.Now.ToString() + "------";
                }

                // 遍历所有的文件和目录 
                foreach (string file in fileList)
                {
                    // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 
                    if (System.IO.Directory.Exists(file))
                    {
                        CopyDir(file, aimPath + System.IO.Path.GetFileName(file));
                        if (count == 0)
                        {
                            str += file + ",";
                        }
                    }
                    // 否则直接Copy文件 
                    else
                    {
                        System.IO.File.Copy(file, aimPath + System.IO.Path.GetFileName(file), true);
                        if (count == 0)
                        {
                            str += file + ",";
                        }
                    }
                }

                if (System.IO.File.Exists(fullPath))
                {
                    using (StreamWriter sw = new StreamWriter(fullPath, true, Encoding.Default))
                    {
                        sw.WriteLine(str);
                    }
                }
                else
                {
                    File.Create(fullPath).Close();

                    using (StreamWriter sw = new StreamWriter(fullPath, true, Encoding.Default))
                    {
                        sw.WriteLine(str);
                    }
                }
                copyFile = true;

            }
            catch (Exception e)
            {
                //MessageBox.Show(e.ToString());
            }
            return copyFile;
        }

        /// <summary>
        /// 恢复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRestoration_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string foldPath = dialog.SelectedPath;
                //this.txtFile.Text = foldPath;
                if (CopyDir(foldPath, targetPath))
                {
                    MessageBox.Show("恢复成功!");
                }
                else
                {
                    MessageBox.Show("恢复失败!");
                }
            }
        }

      /// <summary>
      /// 定时
      /// </summary>
      /// <param name="sender"></param>
      /// <param name="e"></param>
        private void btnTimeUpdate_Click(object sender, EventArgs e)
        {
            string dt = DateTime.Now.ToString("HH:mm");
            string ver = "^((0[0-9]|1[0-9]|2[0-3]):(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]))$";
            timer.Interval = 30000;

            //判断是否选中
            if (!chbUpdate.Checked)
            {
                txtTime.Enabled = true;
            }
            else
            {
                txtTime.Enabled = false;
            }


            if (Timing != "" && Regex.IsMatch(Timing, ver))
            {
                if (dt == Timing)
                {
                    timer.Tick += new EventHandler(timer_Tick);
                }
            }
            else
            {
                MessageBox.Show("请正确填写时间!");
                this.chbUpdate.Checked = false;
                this.txtTime.Text = "";
            }
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            backup();
            CopyDir(filePath, targetPath);
            this.Close();
        }

        
        /// <summary>
        /// 查看日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLog_Click(object sender, EventArgs e)
        {          
            if (File.Exists(fullPath))
            {
                System.Diagnostics.Process.Start(fullPath);
            }
            else
            {
                File.Create(fullPath).Close();
                System.Diagnostics.Process.Start(fullPath);
            }
        }

        /// <summary>
        /// Backup
        /// </summary>
        public void backup()
        {
            count = 1;
            if (Directory.Exists(backPath))
            {
                DirectoryInfo dirpath = Directory.CreateDirectory(backPath + DateTime.Now.ToString("yyyy-MM-dd"));
                string backFile = dirpath.FullName.ToString();
                CopyDir(targetPath, backFile);
            }
            else
            {
                Directory.CreateDirectory(backPath);
                DirectoryInfo dirpath = Directory.CreateDirectory(backPath + DateTime.Now.ToString("yyyy-MM-dd"));
                string backFile = dirpath.FullName.ToString();
                CopyDir(targetPath, backFile);
            }
            count = 0;
        }
    }
}

2.App.config文件代码:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!--源地址-->
    <add key="FilePath" value="C:\Users\xiaobai\Desktop\新建文件夹"/>
    <!--目标地址-->
    <add key="TargetPath" value="D:\test\" />
    <!--备份地址-->
    <add key="backUpPath" value="D:\backup\" />
    <!--设置定时时间-->
    <add key="Timing" value="14:50" />
  </appSettings>
</configuration>

3.截图:

bubuko.com,布布扣bubuko.com,布布扣bubuko.com,布布扣bubuko.com,布布扣

Winform文件夹内容同步更新、备份、日志、恢复,布布扣,bubuko.com

Winform文件夹内容同步更新、备份、日志、恢复

标签:c#   备份   

原文地址:http://blog.csdn.net/lisenyang/article/details/36866773

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!