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

C#编写自动差异备份文件夹

时间:2018-03-23 16:23:44      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:dna   status   后缀名   def   获取   固定   img   put   work   

    手动或定时将源文件夹中的全部文件自动与目标文件夹中的文件做对比,如果源文件夹中的文件更新,则将其复制到目标文件夹中替换目标文件夹中的文件。

界面:

技术分享图片

界面中的内容:

序号

控件类型

名称

作用

1

TextBox

tbxSourcePath

源文件夹路径

2

TextBox

tbxDestPath

目标文件夹路径

3

NumericUpDown

numTimer

定时备份时间

4

ComboBox

cbbCycle

备份时间单位

5

CheckBox

ckbAuto

是否开启定时备份

6

Button

btnSourceSelect

选择源文件夹

7

Button

btnDestSelect

选择目标文件夹

8

Button

btnBackups

开始备份

9

statusStrip

toolStripStatusLabel1

备份是否成功信息

10

statusStrip

toolStripStatusLabel3

当前时间

代码:

窗口初始化:

 1         private void Form1_Load(object sender, EventArgs e)
 2         {
 3             //状态条初始化
 4             toolStripStatusLabel1.Text = "";
 5             toolStripStatusLabel2.Text = "";
 6             toolStripStatusLabel3.Text = DateTime.Now.ToString("HH: mm:ss");
 7             //固定窗口大小
 8             this.MaximizeBox = false;
 9             this.MaximumSize = this.Size;
10             this.MinimumSize = this.Size;
11 
12             ckbAuto.Checked = false;//自动备份复选框默认不选择
13             numTimer.Value = 10;//设置默认定时时间为10分钟
14             tbxSourcePath.Text = "";//初始化源路径
15             tbxDestPath.Text = "";//初始化目标路径
16             //初始化下拉列表控件
17             cbbCycle.Items.Clear();
18             cbbCycle.Items.Add("分钟");
19             cbbCycle.Items.Add("小时");
20             cbbCycle.Items.Add("");
21             cbbCycle.SelectedIndex = 0;
22 
23         }

 

选择源文件夹与目标文件夹路径:

 1         //选择文件路径
 2         private string ChooseFolder()
 3         {
 4             string result = "";
 5             //选择文件夹对话框
 6             FolderBrowserDialog a = new FolderBrowserDialog();
 7             a.Description = "请选择源文件夹路径";
 8             a.RootFolder = Environment.SpecialFolder.MyComputer;
 9             a.ShowNewFolderButton = true;
10 
11             if (a.ShowDialog() == DialogResult.OK)//判断是否选择了路径
12             {
13                 result = a.SelectedPath;
14             }
15             else
16             {
17                 result = "";
18             }
19 
20             return result;
21         }
22 
23         private void btnSourceSelect_Click(object sender, EventArgs e)
24         {
25             tbxSourcePath.Text = ChooseFolder();
26         }
27 
28         private void btnObjectSelect_Click(object sender, EventArgs e)
29         {
30             tbxDestPath.Text = ChooseFolder();
31         }

 

备份文件函数:

  1         //备份
  2         private bool Backups()
  3         {
  4             bool result = true;
  5             working = true;
  6             //判断是否选择了文件夹
  7             if (tbxSourcePath.Text.Trim() == "" || tbxDestPath.Text.Trim() == "")
  8             {
  9                 result = false;
 10                 MessageBox.Show("未选择文件夹路径!","错误提示");
 11                 return result;
 12             }
 13             //判断文件夹是否存在
 14             if (!Directory.Exists(tbxSourcePath.Text) || !Directory.Exists(tbxDestPath.Text))
 15             {
 16                 result = false;
 17                 MessageBox.Show("文件夹路径非法!", "错误提示");
 18                 return result;
 19             }
 20             //获取路径下的所有文件夹与文件
 21             string[] sourceDirectorys = Directory.GetDirectories(tbxSourcePath.Text);
 22             string[] destDirectorys = Directory.GetDirectories(tbxDestPath.Text);
 23             string[] sourceFiles = Directory.GetFiles(tbxSourcePath.Text);
 24             string[] destFiles = Directory.GetFiles(tbxDestPath.Text);
 25             
 26             if(!BackupFiles(sourceFiles, destFiles, tbxDestPath.Text)) result = false;
 27             if(!BackupDirectory(sourceDirectorys, destDirectorys, tbxDestPath.Text)) result = false;
 28 
 29             working = false;
 30             return result;
 31         }
 32 
 33         //备份文件
 34         private bool BackupFiles(string[] sourceFiles, string[] destFiles,string destPath)
 35         {
 36             bool result = true;
 37             try
 38             {
 39                 for (int i = 0; i < sourceFiles.Length; i++)
 40                 {
 41                     bool shouldCopy = true;
 42                     //获取源文件的名称含后缀名
 43                     string sourcename1 = NiceFileProduce.DecomposePathAndName(sourceFiles[i],NiceFileProduce.DecomposePathEnum.NameOnly);
 44                     string sourcename2 = NiceFileProduce.DecomposePathAndName(sourceFiles[i], NiceFileProduce.DecomposePathEnum.ExtensionOnly).ToLower();
 45                     string sourcename = sourcename1 + sourcename2;
 46 
 47                     DateTime ta = File.GetLastWriteTime(sourceFiles[i]);//获取源文件左后写入时间
 48 
 49                     for (int j = 0; j < destFiles.Length; j++)
 50                     {
 51                         //获取目标路径文件的名称含后缀名
 52                         string destname1 = NiceFileProduce.DecomposePathAndName(destFiles[j], NiceFileProduce.DecomposePathEnum.NameOnly);
 53                         string destname2 = NiceFileProduce.DecomposePathAndName(destFiles[j], NiceFileProduce.DecomposePathEnum.ExtensionOnly).ToLower();
 54                         string destname = destname1 + destname2;
 55                         if (sourcename == destname)
 56                         {
 57                             DateTime tb = File.GetLastWriteTime(destFiles[j]);//获取目标文件左后写入时间
 58                             if (DateTime.Compare(ta, tb) <= 0)//判断源文件与目标文件那个更新修改
 59                             {
 60                                 shouldCopy = false;
 61                             }
 62                         }
 63                     }
 64                     //拷贝文件
 65                     if (shouldCopy)
 66                     {
 67                         string destpath = destPath + @"\" + sourcename;
 68                         if (File.Exists(destpath))
 69                         {
 70                             File.Delete(destpath);
 71                         }
 72                         File.Copy(sourceFiles[i], destpath);
 73                     }
 74                 }
 75             }
 76             catch(Exception ex)
 77             {
 78                 result = false;
 79                 MessageBox.Show("拷贝文件失败:"+ex.Message,"错误提示");
 80             }
 81             return result;
 82         }
 83 
 84         //备份文件夹
 85         private bool BackupDirectory(string[] sourceDirectorys, string[] destDirectorys, string destPath)
 86         {
 87             bool result = true;
 88             try
 89             {
 90                 for (int i = 0; i < sourceDirectorys.Length; i++)
 91                 {
 92                     string sourcename = NiceFileProduce.DecomposePathAndName(sourceDirectorys[i], NiceFileProduce.DecomposePathEnum.NameAndExtension);
 93                     string destpath = destPath + @"\" + sourcename;
 94                     if (!Directory.Exists(destpath))
 95                     {
 96                         Directory.CreateDirectory(destpath);
 97                     }
 98                     
 99                     //获取路径下的所有文件夹与文件
100                     string[] sourceDirectorys2 = Directory.GetDirectories(sourceDirectorys[i]);
101                     string[] destDirectorys2 = Directory.GetDirectories(destpath);
102                     string[] sourceFiles = Directory.GetFiles(sourceDirectorys[i]);
103                     string[] destFiles = Directory.GetFiles(destpath);
104 
105                     if (!BackupFiles(sourceFiles, destFiles, destpath)) result = false;
106                     
107                     if (sourceDirectorys2.Length != 0)
108                     {
109                         if(!BackupDirectory(sourceDirectorys2, destDirectorys2, destpath)) result = false;
110                     }
111                 }
112         }
113             catch(Exception ex)
114             {
115                 result = false;
116                 MessageBox.Show("拷贝文件夹失败:"+ex.Message,"错误提示");
117             }
118             return result;
119         }

 

手动备份按钮:

 1         private void btnBackups_Click(object sender, EventArgs e)
 2         {
 3             if (working)
 4             {
 5                 toolStripStatusLabel1.Text = "正在备份中,稍后再试";
 6             }
 7             else
 8             {
 9                 toolStripStatusLabel1.Text = "备份开始";
10                 if (Backups())
11                 {
12                     toolStripStatusLabel1.Text = "手动备份成功" + DateTime.Now.ToString(" yyyy年mm月dd日 HH:mm:ss");
13                 }
14                 else
15                 {
16                     toolStripStatusLabel1.Text = "手动备份失败" + DateTime.Now.ToString(" yyyy年mm月dd日 HH:mm:ss");
17                 }
18             }  
19         }

 

自动备份定时器设置:

 1         private void ckbAuto_CheckedChanged(object sender, EventArgs e)
 2         {
 3             int time = 600000;
 4             if (ckbAuto.Checked)
 5             {
 6                 if (cbbCycle.Text == "分钟")
 7                 {
 8                     time = Convert.ToInt32(numTimer.Value) * 1000 * 60;
 9                 }
10                 else if (cbbCycle.Text == "小时")
11                 {
12                     time = Convert.ToInt32(numTimer.Value) * 1000 * 60 * 60;
13                 }
14                 else if (cbbCycle.Text == "")
15                 {
16                     time = Convert.ToInt32(numTimer.Value) * 1000 * 60 * 60 * 24;
17                 }
18                 cbbCycle.Enabled = false;
19                 numTimer.Enabled = false;
20                 timer1.Interval = time;
21                 timer1.Start();
22             }
23             else
24             {
25                 timer1.Stop();
26                 cbbCycle.Enabled = true;
27                 numTimer.Enabled = true;
28             }
29         }

 

自动备份定时器:

 1         private void timer1_Tick(object sender, EventArgs e)
 2         {
 3             if (working)
 4             {
 5                 toolStripStatusLabel1.Text = "正在备份中,稍后再试";
 6             }
 7             else
 8             {
 9                 toolStripStatusLabel1.Text = "备份开始";
10                 if (Backups())
11                 {
12                     toolStripStatusLabel1.Text = "定时备份成功" + DateTime.Now.ToString(" yyyy年mm月dd日 HH:mm:ss");
13                 }
14                 else
15                 {
16                     toolStripStatusLabel1.Text = "定时备份失败" + DateTime.Now.ToString(" yyyy年mm月dd日 HH:mm:ss");
17                 }
18             }
19         }

 

当前时间显示:

1         private void timer2_Tick(object sender, EventArgs e)
2         {
3             toolStripStatusLabel3.Text = DateTime.Now.ToString("HH: mm:ss");
4         }

 

分解文件路径函数:

 1     public class NiceFileProduce
 2     {
 3         //分解路径用枚举
 4         public enum DecomposePathEnum
 5         {
 6             PathOnly = 0,//仅返回路径
 7             NameAndExtension = 1,//返回文件名+扩展名
 8             NameOnly = 2,//仅返回文件名
 9             ExtensionOnly = 3,//仅返回扩展名(带.)
10 
11         }
12 
13         //------------【函数:将文件路径分解】------------  
14 
15         //filePath文件路径
16         //DecomposePathEnum返回类型
17         //------------------------------------------------
18         public static string DecomposePathAndName(string filePath, DecomposePathEnum decomposePathEnum)
19         {
20             string result = "";
21             switch (decomposePathEnum)
22             {
23                 case DecomposePathEnum.PathOnly://仅返回路径
24                     if (filePath.LastIndexOf("\\") < 0)
25                     {
26                         result = filePath;
27                     }
28                     else
29                     {
30                         result = filePath.Substring(0, filePath.LastIndexOf("\\"));
31                     }
32                     break;
33                 case DecomposePathEnum.NameAndExtension://返回文件名+扩展名
34                     if (filePath.LastIndexOf("\\") < 0)
35                     {
36                         result = filePath;
37                     }
38                     else
39                     {
40                         result = filePath.Substring(filePath.LastIndexOf("\\") + 1);
41                     }
42                     break;
43                 case DecomposePathEnum.NameOnly://仅返回文件名
44                     if (filePath.LastIndexOf("\\") < 0)
45                     {
46                         if (filePath.LastIndexOf(".") < 0)
47                         {
48                             result = filePath;
49                         }
50                         else
51                         {
52                             result = filePath.Substring(0, filePath.LastIndexOf(".") - filePath.LastIndexOf("\\") - 1);
53                         }
54                     }
55                     else
56                     {
57                         if (filePath.LastIndexOf(".") < 0)
58                         {
59                             result = filePath.Substring(filePath.LastIndexOf("\\") + 1);
60                         }
61                         else
62                         {
63                             result = filePath.Substring(filePath.LastIndexOf("\\") + 1, filePath.LastIndexOf(".") - filePath.LastIndexOf("\\") - 1);
64                         }
65                     }
66                     break;
67                 case DecomposePathEnum.ExtensionOnly://仅返回扩展名(带.)
68                     if (filePath.LastIndexOf(".") < 0)
69                     {
70                         result = filePath;
71                     }
72                     else
73                     {
74                         result = filePath.Substring(filePath.LastIndexOf("."));
75                     }
76                     break;
77                 default://
78                     result = "";
79                     break;
80             }
81             return result;
82         }
83     }

 

C#编写自动差异备份文件夹

标签:dna   status   后缀名   def   获取   固定   img   put   work   

原文地址:https://www.cnblogs.com/nicewe/p/8630565.html

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