热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

C#开发的定时自动拷贝文件到别处,并删除过期备份文件,支持网上邻居拷贝...

2018年7月7日开发工具VS2013.net框架2.0SQLserver的备份文件只可以备份在本机,只有一份,这个软件可以定时把备份文件拷贝到别的机器

2018年7月7日

开发工具VS2013  .net 框架 2.0

SQL server的备份文件只可以备份在本机,只有一份,这个软件可以定时把备份文件拷贝到别的机器,作为另外的备份,还可以在成功备份后自动删除过期的文件,没有成功备份,不删除过期文件,以免误删,除非手动删除。

拷贝文件过程中没有进度条提示。

    

写了4个类,没写字段和属性,只写方法,很简单。

 

///

Ini.cs  //读写配置文件,使用设置可以保存下来,下次打开软件,不用重新设置

1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Runtime.InteropServices;
5
6 namespace AutoCopy
7 {
8 class Ini
9 {
10 [DllImport("kernel32")]
11 private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
12 [DllImport ("kernel32")]
13 private static extern int GetPrivateProfileString(string section, string key, string def,StringBuilder retVal, int size,string filePath);
14
15 ///


16 /// 读取ini
17 ///

18 /// 数据分组
19 /// 关键字
20 ///
21 /// ini文件地址
22 /// 关键字对应的值,没有时用默认值
23 public static string readini(string group, string key, string default_value, string filepath)
24 {
25 StringBuilder temp = new StringBuilder();
26 GetPrivateProfileString(group,key,default_value,temp, 255, filepath);
27 return temp.ToString();
28 }
29 ///
30 /// 存储ini
31 ///

32 /// 数据分组
33 /// 关键字
34 /// 关键字对应的值
35 /// ini文件地址
36 public static void writeini(string group, string key, string value, string filepath)
37 {
38 WritePrivateProfileString(group, key, value, filepath);
39 }
40
41 }
42 }

 

///

FileOprater.cs //文件操作类,

1 using System;
2 using System.Collections;
3 using System.Collections.Generic;
4 using System.IO;
5 using System.Text;
6 using System.Windows.Forms;
7
8 namespace AutoCopy
9 {
10 class FileOprater
11 {
12 public FileOprater(){}
13
14 ///


15 /// 读取路径上的文件列表
16 ///

17 /// 文件路径
18 /// == 或者 >=
19 /// 用numberUpDown的值
20 ///
21 public ArrayList getFileList(string Path, string compare, int days)
22 {
23 try
24 {
25 string[] dir = Directory.GetFiles(Path);
26 ArrayList _fileList = new ArrayList();
27 for (int dirIndex = 0; dirIndex )
28 {
29 DateTime fileLastWriteTime = File.GetLastWriteTime(dir[dirIndex].ToString());
30 TimeSpan timespan = DateTime.Today.Date - fileLastWriteTime.Date;
31 if (compare == "==")
32 {
33 if (timespan.Days == 0)
34 {
35 _fileList.Add(dir[dirIndex].ToString());
36 }
37 }
38 else
39 {
40 //TimeSpan timespan = DateTime.Today.Date - fileLastWriteTime.Date;
41 if (timespan.Days >= days)
42 {
43 _fileList.Add(dir[dirIndex].ToString());
44 }
45 }
46
47 }
48 return _fileList;
49 }
50 catch(Exception e)
51 {
52 MessageBox.Show(e.ToString(),"错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
53 return null;
54
55 }
56
57 }
58
59 ///
60 /// 拷贝文件,用FileStream buffer来写入,大文件也没问题
61 ///

62 /// 源文件路径
63 /// 目标文件路径
64 public void CopyFiles(string SourcePath, string DestinyPath)
65 { //1创建一个负责读取的流
66 using (FileStream fsRead = new FileStream(SourcePath, FileMode.Open, FileAccess.Read))
67 {//创建一个负责写入的流
68 using (FileStream fsWrite = new FileStream(DestinyPath, FileMode.OpenOrCreate, FileAccess.Write))
69 {
70 byte[] buffer = new byte[1024 * 1024 * 5];
71 while (true)
72 {
73 int r = fsRead.Read(buffer, 0, buffer.Length);
74 //如果返回一个0,就意味什么都没有读取到,读取完了
75 if (r == 0)
76 {
77 break;
78 }
79 fsWrite.Write(buffer, 0, r);
80 }
81 }
82
83 }
84
85 }
86
87 public void DeleteFiles(string Path)
88 {
89 File.Delete(Path);
90
91 }
92
93 }
94 }

 

///

MyListBox.cs

//把文件显示在列表框的类

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Collections;namespace AutoCopy
{
class MyListBox
{
public MyListBox() { }
internal Boolean showFilesList(ArrayList fileList,ListBox listbox )
{
//定义数组,用于保存文件路径
if (fileList != null)
{
for (int index = 0; index )
{
listbox.Items.Add(fileList[index].ToString());
}
return true;
}
else
return false;}}
}

 

///

LogWriter.cs 

 //最后的这个是写入日志文件的类。

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;namespace AutoCopy
{
class LogWriter
{
public LogWriter() { }internal void writeLog(string str)
{
string AppPath = System.Windows.Forms.Application.StartupPath + "\\Log.txt";
if (!File.Exists(AppPath))
{
File.CreateText(AppPath);
}
using (FileStream fs = new FileStream(AppPath, FileMode.Append, FileAccess.Write))
{
Byte[] info
=
new UTF8Encoding(true).GetBytes(DateTime.Now.ToString() + " "+str+"\r\n");// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}}
}

 

//

Form1.cs  //界面里的操作代码写的有点多,显得有点零乱。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;namespace AutoCopy
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//源文件目录浏览按钮private void buttonSource_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
textBoxSource.Text
= folderBrowserDialog1.SelectedPath.ToString();}
//目标文件目录浏览按钮
private void buttonDestiny_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
textBoxDestiny.Text
= folderBrowserDialog1.SelectedPath.ToString();
}
//新建FileOprater对象
FileOprater fo=new FileOprater();//新建MyListBox对象
MyListBox mylistbox=new MyListBox();//新建LogWriter对象
LogWriter lw = new LogWriter();//新建Ini对象
//Ini ini = new Ini();//托盘区图标功能
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
//还原窗体显示
WindowState = FormWindowState.Normal;
//激活窗体并给予它焦点
this.Activate();
//任务栏区显示图标
this.ShowInTaskbar = true;
//托盘区图标隐藏
notifyIcon1.Visible = false;
}}
//隐藏程序窗口到托盘区
private void Form1_SizeChanged(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
//隐藏任务栏区图标
this.ShowInTaskbar = false;
//图标显示在托盘区
notifyIcon1.Visible = true;
}
}
//关闭程序确认对话框
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("是否确定退出程序?","退出",MessageBoxButtons.OKCancel,MessageBoxIcon.Question) == DialogResult.OK)
{
//关闭所有的进程
this.Dispose();
this.Close();
}
else
{
e.Cancel
= true;
}
}
private void buttonOK_Click(object sender, EventArgs e)
{TodayFileslistBox.Items.Clear();
//清空列表框

mylistbox.showFilesList(fo.getFileList(textBoxSource.Text.Trim(),
"==",0),TodayFileslistBox);//显示文件列表在列表框if (TodayFileslistBox.Items != null) //如果列表不为空(有文件)
{
for (int i = 0; i //循环
{
string strName = TodayFileslistBox.Items[i].ToString().Substring(TodayFileslistBox.Items[i].ToString().LastIndexOf("\\"));try
{
StatusLabel2.Text
= strName + "正在复制";fo.CopyFiles(TodayFileslistBox.Items[i].ToString(), textBoxDestiny.Text + strName);StatusLabel2.Text = strName + " 复制完成";lw.writeLog(TodayFileslistBox.Items[i].ToString() + " 复制成功");//写入日志文件
//以上代码跟Timer1的执行代码有重复,下面也有说明

}
catch (Exception ex)
{
StatusLabel2.Text
= "备份过程出错,请查看日志文件Log.txt";
lw.writeLog(ex.ToString());
}}
}}
private void Form1_Load(object sender, EventArgs e)
{
updateFileListlabel();
updateStatusLabel();
StatusLabel2.Text
= "";//测试读写set.ini文件的代码
//string value = Ini.readini("group1", "source", "default_value1", ".\\set.ini");
//Ini.writeini("group2", "key2", value, ".\\set.ini");
InitializeSets();}private void InitializeSets()
{
textBoxSource.Text
= Ini.readini("group1", "source", "I:\\backup", ".\\set.ini");
textBoxDestiny.Text
= Ini.readini("group1", "destiny", "D:\\backup", ".\\set.ini");
checkBoxDel.Checked
= Convert.ToBoolean(Ini.readini("group1", "deleteChecked", "true", ".\\set.ini"));
DaysNumericUpDown.Value
= Convert.ToDecimal(Ini.readini("group1", "days", "3", ".\\set.ini"));
dateTimePicker1.Value
= Convert.ToDateTime(Ini.readini("group1", "actionTime", "20:00:00", ".\\set.ini"));
}
private void updateStatusLabel()
{
StatusLabel1.Text
="备份时间:"+dateTimePicker1.Value.ToShortTimeString();
}
//刷新N天前文件列表标签
private void updateFileListlabel()
{
FileListlabel.Text
= DaysNumericUpDown.Value + "天前的文件列表:";
}
//更改天数时,刷新N天前文件列表标签
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
updateFileListlabel();
Ini.writeini(
"group1", "days", DaysNumericUpDown.Value.ToString(), ".\\set.ini");}private void buttonUpdateTodayFileList_Click(object sender, EventArgs e)
{
//清空列表
TodayFileslistBox.Items.Clear();
ArrayList filelist
= fo.getFileList(textBoxSource.Text.Trim(),"==",0);
mylistbox.showFilesList(filelist,TodayFileslistBox);}
private void buttonUpdateNdaysFileList_Click(object sender, EventArgs e)
{
#region 模块化的代码,没用
//FillListBox(NdaysBeforeFilesListBox, textBoxDestiny.Text.Trim(), NdayBeforeFileslabel,Convert.ToInt16(DaysNumericUpDown.Value),"<&#61;");
#endregion
fillNdaysListBox();
}
private void fillNdaysListBox()
{
NdaysBeforeFilesListBox.Items.Clear();
ArrayList filelist
&#61; fo.getFileList(textBoxDestiny.Text.Trim(), "&#61;>", Convert.ToInt16(DaysNumericUpDown.Value));
mylistbox.showFilesList(filelist, NdaysBeforeFilesListBox);
}
private void timer1_Tick(object sender, EventArgs e)
{
#region MyRegionif (DateTime.Now.ToShortTimeString() &#61;&#61; dateTimePicker1.Value.ToShortTimeString())
{
//显示今天文件在列表框
TodayFileslistBox.Items.Clear();
mylistbox.showFilesList(fo.getFileList(textBoxSource.Text.Trim(),
"&#61;&#61;", 0), TodayFileslistBox);
//拷贝文件
if (TodayFileslistBox.Items !&#61; null) //如果没有当天的文件可复制&#xff0c;刚不删除旧已备份的文件
{
for (int i &#61; 0; i )
{
string strName &#61; TodayFileslistBox.Items[i].ToString().Substring(TodayFileslistBox.Items[i].ToString().LastIndexOf("\\"));try
{
StatusLabel2.Text
&#61; "正在复制文件&#xff1a;" &#43; strName;fo.CopyFiles(TodayFileslistBox.Items[i].ToString(), textBoxDestiny.Text &#43; strName);StatusLabel2.Text &#61; strName&#43; " 复制完成";lw.writeLog(TodayFileslistBox.Items[i].ToString() &#43; " 复制成功");//写入日志文件//以上代码跟“拷贝文件”按钮的代码有重复&#xff0c;之所以不能重构成方法&#xff0c;是因为下面两行Timer1代码包含了删除过期文件的代码。
//暂时没找到更好的方法&#xff0c;以后学习到更好的方法再改正。也希望同学们不吝赐教。

}
catch (Exception ex)
{
StatusLabel2.Text
&#61; "备份过程出错&#xff0c;请查看日志文件Log.txt";
lw.writeLog(ex.ToString());
}
}

  //如果没有当天的文件可复制&#xff0c;刚不删除旧已备份的文件
  //显示N天前的文件在列表框
  fillNdaysListBox();
  //删除文件
  delfiles();


}
#endregion
}
}
private void buttonDelete_Click(object sender, EventArgs e)
{
if (MessageBox.Show("你确定要删除文件吗&#xff0c;删除后不可恢复&#xff01;&#xff01;","确定删除&#xff01;&#xff01;",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Warning,MessageBoxDefaultButton.Button3) &#61;&#61; DialogResult.Yes)
{
if (MessageBox.Show("确定要删&#xff01;&#xff0c;不可恢复哦&#xff01;&#xff01;", "真的要删除&#xff01;&#xff01;", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button3) &#61;&#61; DialogResult.Yes)
{
fillNdaysListBox();
delfiles();
}
}}
private void delfiles()
{
if (checkBoxDel.Checked)
{
for (int i &#61; 0; i )
{
string path &#61; NdaysBeforeFilesListBox.Items[i].ToString();try
{
fo.DeleteFiles(path);
StatusLabel2.Text
&#61; path &#43; " 删除成功";
lw.writeLog(path
&#43; " 删除成功");
}
catch (Exception e)
{
StatusLabel2.Text
&#61; path &#43; " 删除失败&#xff0c;请查看日志文件&#xff01;";
lw.writeLog(e.ToString());
}
}
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
updateStatusLabel();
Ini.writeini(
"group1", "actionTime", dateTimePicker1.Value.ToShortTimeString(), ".\\set.ini");
}
private void textBoxSource_TextChanged(object sender, EventArgs e)
{
Ini.writeini(
"group1", "source", textBoxSource.Text.Trim() , ".\\set.ini");
}
private void textBoxDestiny_TextChanged(object sender, EventArgs e)
{
Ini.writeini(
"group1", "destiny", textBoxDestiny.Text.Trim(), ".\\set.ini");
}
private void checkBoxDel_CheckedChanged(object sender, EventArgs e)
{
Ini.writeini(
"group1", "deleteChecked", checkBoxDel.Checked.ToString(), ".\\set.ini");
}}
}

 

源码下载&#xff1a;https://files.cnblogs.com/files/YJkong/AutoCopy.rar

转:https://www.cnblogs.com/YJkong/p/9277099.html



推荐阅读
  • 海马s5近光灯能否直接更换为H7?
    本文主要介绍了海马s5车型的近光灯是否可以直接更换为H7灯泡,并提供了完整的教程下载地址。此外,还详细讲解了DSP功能函数中的数据拷贝、数据填充和浮点数转换为定点数的相关内容。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 本文介绍了三种方法来实现在Win7系统中显示桌面的快捷方式,包括使用任务栏快速启动栏、运行命令和自己创建快捷方式的方法。具体操作步骤详细说明,并提供了保存图标的路径,方便以后使用。 ... [详细]
  • Android源码深入理解JNI技术的概述和应用
    本文介绍了Android源码中的JNI技术,包括概述和应用。JNI是Java Native Interface的缩写,是一种技术,可以实现Java程序调用Native语言写的函数,以及Native程序调用Java层的函数。在Android平台上,JNI充当了连接Java世界和Native世界的桥梁。本文通过分析Android源码中的相关文件和位置,深入探讨了JNI技术在Android开发中的重要性和应用场景。 ... [详细]
  • 本文介绍了如何清除Eclipse中SVN用户的设置。首先需要查看使用的SVN接口,然后根据接口类型找到相应的目录并删除相关文件。最后使用SVN更新或提交来应用更改。 ... [详细]
  • 本文介绍了在CentOS上安装Python2.7.2的详细步骤,包括下载、解压、编译和安装等操作。同时提供了一些注意事项,以及测试安装是否成功的方法。 ... [详细]
  • 本文介绍了在iOS开发中使用UITextField实现字符限制的方法,包括利用代理方法和使用BNTextField-Limit库的实现策略。通过这些方法,开发者可以方便地限制UITextField的字符个数和输入规则。 ... [详细]
  • 本文介绍了使用哈夫曼树实现文件压缩和解压的方法。首先对数据结构课程设计中的代码进行了分析,包括使用时间调用、常量定义和统计文件中各个字符时相关的结构体。然后讨论了哈夫曼树的实现原理和算法。最后介绍了文件压缩和解压的具体步骤,包括字符统计、构建哈夫曼树、生成编码表、编码和解码过程。通过实例演示了文件压缩和解压的效果。本文的内容对于理解哈夫曼树的实现原理和应用具有一定的参考价值。 ... [详细]
  • 本文介绍了一种轻巧方便的工具——集算器,通过使用集算器可以将文本日志变成结构化数据,然后可以使用SQL式查询。集算器利用集算语言的优点,将日志内容结构化为数据表结构,SPL支持直接对结构化的文件进行SQL查询,不再需要安装配置第三方数据库软件。本文还详细介绍了具体的实施过程。 ... [详细]
  • 本文介绍了使用PHP实现断点续传乱序合并文件的方法和源码。由于网络原因,文件需要分割成多个部分发送,因此无法按顺序接收。文章中提供了merge2.php的源码,通过使用shuffle函数打乱文件读取顺序,实现了乱序合并文件的功能。同时,还介绍了filesize、glob、unlink、fopen等相关函数的使用。阅读本文可以了解如何使用PHP实现断点续传乱序合并文件的具体步骤。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 图解redis的持久化存储机制RDB和AOF的原理和优缺点
    本文通过图解的方式介绍了redis的持久化存储机制RDB和AOF的原理和优缺点。RDB是将redis内存中的数据保存为快照文件,恢复速度较快但不支持拉链式快照。AOF是将操作日志保存到磁盘,实时存储数据但恢复速度较慢。文章详细分析了两种机制的优缺点,帮助读者更好地理解redis的持久化存储策略。 ... [详细]
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 本文介绍了Web学习历程记录中关于Tomcat的基本概念和配置。首先解释了Web静态Web资源和动态Web资源的概念,以及C/S架构和B/S架构的区别。然后介绍了常见的Web服务器,包括Weblogic、WebSphere和Tomcat。接着详细讲解了Tomcat的虚拟主机、web应用和虚拟路径映射的概念和配置过程。最后简要介绍了http协议的作用。本文内容详实,适合初学者了解Tomcat的基础知识。 ... [详细]
author-avatar
cjaklxn_490
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有