using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
namespace _6_2copy
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void copy(string sourceDirPath, string SaveDirPath)//文件复制函数
{
string tt = DateTime.Now.TimeOfDay.ToString("hhmmss");//获取当前系统时间
string time = dateTimePicker1.Value.ToString("HHmmss");//获取用户设定的自动备份时间
//当到达用户设定的时间时,执行一下操作
if (tt == time)
{
try
{
string month = DateTime.Now.Month.ToString();//获取系统时间的月
string day = DateTime.Now.Day.ToString();//获取系统时间的日
if (!Directory.Exists(SaveDirPath))//若是没有目标文件夹
{
//创建
Directory.CreateDirectory(SaveDirPath);
}
string[] files = Directory.GetFiles(sourceDirPath);//获取当前备份路径下所有文件
foreach (string file in files)//循环遍历获得的文件
{
string pFilePath = SaveDirPath + "\\" + Path.GetFileName(file);//获取备份文件名以及路径
if (File.Exists(pFilePath))//如果该文件已存在
continue;//跳过下一个语句
File.Copy(file, pFilePath, true);//该文件不存在,复制
}
string[] dirs = Directory.GetDirectories(sourceDirPath);//获取当前路径下所有文件夹(目录文件)
//递归,遍历文件夹
foreach (string dir in dirs)//循环遍历所有文件夹
{
copy(dir, SaveDirPath + "\\"+ Path.GetFileName(dir));//调用copy函数获取下一级目录里面的内容
}
}
catch(Exception ex)//异常处理
{
MessageBox.Show(ex.Message);
}
}
}
private void button1_Click(object sender, EventArgs e)//备份路径按钮点击事件
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)//选中路径后
{
textBox1.Text = folderBrowserDialog1.SelectedPath;//将选中的路径显示在 textBox1
}
}
private void button2_Click(object sender, EventArgs e)//目标路径按钮点击事件
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)//选中路径后
{
textBox2.Text = folderBrowserDialog1.SelectedPath;//将选中的路径显示在 textBox2
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "按日期生成文件";
timer1.Start();//启动timer1
}
private void timer1_Tick(object sender, EventArgs e)
{
string month = DateTime.Now.Month.ToString();//获取系统时间的月
string day = DateTime.Now.Day.ToString();//获取系统时间的日
string path = textBox2.Text + "/" + month + "月" + "/" + day + "日";//获取系统该自动生成的月和日文件夹的路径
copy(textBox1.Text, path);//调用copy()函数
}
}
}