WinForm folder content sync update, backup, log, restore

Source: Internet
Author: User

Believe that you do the project or processing files often need to use the backup function, here to do a sync Update folder content and backup of the WinForm program, the current address path in the app. config file is set, if you need to change directly with Notepad edit, put code and.

1.CS Code:

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 = C onfigurationmanager.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";//Set the log Address public AutoUpdate () {InitializeComponent ();            This.txtFile.Text = FilePath;            This.txtTo.Text = TargetPath;        This.txtTime.Text = Timing;  }//<summary>//update//</summary>      <param name= "Sender" ></param>//<param name= "E" ></param> private void BT            Nupdate_click (object sender, EventArgs e) {///update simultaneously calls back up backup (); if (FilePath! = "") {if (Copydir (FilePath, TargetPath)) {Mes Sagebox.show ("UPDATE success!!!                "); } else {MessageBox.Show ("UPDATE failed!!!                ");            }} else {MessageBox.Show ("Please set the source address correctly!"); }}///<summary>//update file processing//</summary>//<param name= "Srcpath" ;</param>//<param name= "Aimpath" ></param>///<returns></returns> PR            ivate bool Copydir (string Srcpath, String aimpath) {bool CopyFile = false;  try {//Check whether the destination directory ends with a directory split character if not add               if (aimpath[aimpath.length-1]! = System.IO.Path.DirectorySeparatorChar) {                Aimpath + = System.IO.Path.DirectorySeparatorChar; }//To determine if the target directory exists if it does not exist then new if (!                System.IO.Directory.Exists (Aimpath)) {System.IO.Directory.CreateDirectory (Aimpath);                 }//Get the file list of the source directory, which is an array containing the file and directory path. Use the following method if you point to the file below the copy destination file and do not include the directory string[] fileList = Directory.GetFiles (Srcpath); string[] FileList = System.IO.Directory.GetF                Ilesystementries (Srcpath);                String str = "";                if (count = = 0) {str = DateTime.Now.ToString () + "------"; }//Traverse all files and directories foreach (string file in FileList) {//First Directory processing If the directory is present, recursively copy the files under the directory if (System.IO.Directory.Exists (File) {copydir (file, Aimpath + System.IO.Path.GetFileName (file));                        if (count = = 0) {str + = file + ",";                        }}//otherwise direct copy file 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>//recovery///</summary>/<param name= "Sender" ></param&gt        ;            <param name= "E" ></param> private void Btnrestoration_click (object sender, EventArgs e) {            FolderBrowserDialog dialog = new FolderBrowserDialog (); Dialog.            Description = "Please select file path"; if (dialog. ShowDialog () = = DialogResult.OK) {string foldpath = dialog.                SelectedPath;                This.txtFile.Text = Foldpath; if (Copydir (Foldpath, TargetPath)) {MessageBox.Show ("Recovery succeeded!       ");         } else {MessageBox.Show ("Recovery failed!                "); }}}///<summary>//timing//</summary>/<param name= "Sender" ;</param>//<param name= "E" ></param> private void Btntimeupdate_click (object sender, Event            Args 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;            Determines if the if (!chbupdate.checked) {txttime.enabled = True is checked;            } else {txttime.enabled = false;                if (Timing! = "" "&& Regex.IsMatch (Timing, ver)) {if (dt = = Timing) {Timer.                Tick + = new EventHandler (Timer_tick);   }} else         {MessageBox.Show (please fill in the correct time!)                ");                this.chbUpdate.Checked = false;            This.txtTime.Text = "";            }} private void Timer_tick (object sender, EventArgs e) {backup ();            Copydir (FilePath, TargetPath); This.        Close (); }///<summary>//view Log///</summary>//<param name= "Sender" >&lt        ;/param>//<param name= "E" ></param> private void Btnlog_click (object sender, EventArgs e) {if (file.exists (FullPath)) {System.Diagnostics.Process.Start (FULLP            ATH); } 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 (ba                Ckpath + 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 File Code:

<?xml version= "1.0" encoding= "Utf-8"?><configuration>  <appSettings>    <!--Source Address--    <add key= "FilePath" value= "C:\Users\xiaobai\Desktop\ new Folder"/>    <!--Destination Address--    <add key= " TargetPath "value=" D:\test\ "/>    <!--backup Address--    <add key=" backuppath "value="    D:\backup\ "/> <!--set timing time-    <add key= "Timing" value= "14:50"/>  </appSettings></configuration>

3.:


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.