定时备份文件夹
软件技术国家教学资源库建设项目
——软件开发素材之C# 源代码
一、名称
定时备份文件夹
二、创建或搜集相关信息
搜集单位:重庆电子工程职业学院
搜集时间:2012-08-05
来 源:互联网
三、适用对象
学生、教师、C#及ASP.NET项目开发人员、相关技术人员等。
四、功能简介
实现定时备份文件夹功能。
五、程序代码
程序名称:Program.cs
using System;
using System.Collections.Generic; using System.Linq;
using System.Windows.Forms;
namespace AutoBackup
{
static class Program
{
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
程序名称:Form1.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;
namespace AutoBackup
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dtTime.Value =Convert.ToDateTime(DateTime.Now.ToShortTimeString());
}
private void btnSource_Click(object sender, EventArgs e)
{
FolderBrowserDialog folder = new FolderBrowserDialog();
if (folder.ShowDialog() == DialogResult.OK)
{
txtSource.Text = folder.SelectedPath;
}
}
private void btnDest_Click(object sender, EventArgs e)
{
FolderBrowserDialog folder = new FolderBrowserDialog();
if (folder.ShowDialog() == DialogResult.OK)
{
txtDest.Text = folder.SelectedPath;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (DateTime.Now.ToShortTimeString() == dtTime.Value.ToShortTimeString())
{
if (txtSource.Text != "" && txtDest.Text != "")
{
if (Directory.Exists(txtDest.Text + "\\" + DateTime.Now.Month.ToString()) == false)
{
Directory.CreateDirectory(txtDest.Text + "\\" + DateTime.Now.Month.ToString() + "月");//创建
月份文件夹
}
CopyDirectory(txtSource.Text, txtDest.Text + "\\" + DateTime.Now.Month.ToString() + "\\" +
DateTime.Now.Date.ToShortDateString());
}
}
}
private void CopyDirectory(string sourcePath, string destPath)
{
DirectoryInfo dir = new DirectoryInfo(sourcePath);//实例化
FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();//获取文件夹中所有目录
foreach (FileSystemInfo i in fileinfo)
{
if (i is DirectoryInfo)//判断是文件夹
{
Directory.CreateDirectory(destPath + "\\" + i.Name);//创建文件夹
CopyDirectory(sourcePath + "\\" + i.Name, destPath + "\\" + i.Name);//递归调用
}
else
{
if (File.Exists(destPath + "\\" + i.Name) == false)//文件
{
File.Copy(i.FullName, destPath + "\\" + i.Name);//复制文件
}
}
}
}
}
}
六、运行结果
图131 Program.cs运行结果