Winform檔案夾內容同步更新、備份、日誌、恢複

來源:互聯網
上載者:User

標籤: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.:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.