CBackup.cs
using
System;
using System.Collections.Generic;
using System.Text;
namespace BackupTool
... {
/**//// <summary>
/// 备份类,描述某次备份信息
/// </summary>
class CBackup
...{
private int _pkid;
private string _name;
private DateTime _createdDate;
private int _type;
private int _status;
private string _dbname;
private string _sourceFile;
private string _destFile;
private string _destFolder;
private double _usedTime;
private string _dlpath;
private string _createdUser;
/**//// <summary>
/// 惟一编号
/// </summary>
public int Pkid
...{
set ...{ _pkid = value; }
get ...{ return _pkid; }
}
/**//// <summary>
/// 名称
/// </summary>
public string Name
...{
set ...{ _name = value; }
get ...{ return _name; }
}
/**//// <summary>
/// 创建时间
/// </summary>
public DateTime CreatedDate
...{
set ...{ _createdDate = value; }
get ...{ return _createdDate; }
}
/**//// <summary>
/// 备份类型
/// </summary>
public int Type
...{
set ...{ _type = value; }
get ...{ return _type; }
}
/**//// <summary>
/// 当前备份状态
/// </summary>
public int Status
...{
set ...{ _status = value; }
get ...{ return _status; }
}
/**//// <summary>
/// 项目名称(数据库名称)
/// </summary>
public string DBName
...{
set ...{ _dbname = value; }
get ...{ return _dbname; }
}
/**//// <summary>
/// 源文件(待压缩备份文件)
/// </summary>
public string SourceFile
...{
set ...{ _sourceFile = value; }
get ...{ return _sourceFile; }
}
/**//// <summary>
/// 目标文件
/// </summary>
public string DestFile
...{
set ...{ _destFile = value; }
get ...{ return _destFile; }
}
/**//// <summary>
/// 目标文件 文件夹
/// </summary>
public string DestFolder
...{
set ...{ _destFolder = value; }
get ...{ return _destFolder; }
}
/**//// <summary>
/// 备份花费时间
/// </summary>
public double UsedTime
...{
set ...{ _usedTime = value; }
get ...{ return _usedTime; }
}
/**//// <summary>
/// 下载路径
/// </summary>
public string DLPath
...{
set ...{ _dlpath = value; }
get ...{ return _dlpath; }
}
/**//// <summary>
/// 创建者
/// </summary>
public string CreatedUser
...{
set ...{ _createdUser = value; }
get ...{ return _createdUser; }
}
public CBackup()
...{ }
}
}
using System.Collections.Generic;
using System.Text;
namespace BackupTool
... {
/**//// <summary>
/// 备份类,描述某次备份信息
/// </summary>
class CBackup
...{
private int _pkid;
private string _name;
private DateTime _createdDate;
private int _type;
private int _status;
private string _dbname;
private string _sourceFile;
private string _destFile;
private string _destFolder;
private double _usedTime;
private string _dlpath;
private string _createdUser;
/**//// <summary>
/// 惟一编号
/// </summary>
public int Pkid
...{
set ...{ _pkid = value; }
get ...{ return _pkid; }
}
/**//// <summary>
/// 名称
/// </summary>
public string Name
...{
set ...{ _name = value; }
get ...{ return _name; }
}
/**//// <summary>
/// 创建时间
/// </summary>
public DateTime CreatedDate
...{
set ...{ _createdDate = value; }
get ...{ return _createdDate; }
}
/**//// <summary>
/// 备份类型
/// </summary>
public int Type
...{
set ...{ _type = value; }
get ...{ return _type; }
}
/**//// <summary>
/// 当前备份状态
/// </summary>
public int Status
...{
set ...{ _status = value; }
get ...{ return _status; }
}
/**//// <summary>
/// 项目名称(数据库名称)
/// </summary>
public string DBName
...{
set ...{ _dbname = value; }
get ...{ return _dbname; }
}
/**//// <summary>
/// 源文件(待压缩备份文件)
/// </summary>
public string SourceFile
...{
set ...{ _sourceFile = value; }
get ...{ return _sourceFile; }
}
/**//// <summary>
/// 目标文件
/// </summary>
public string DestFile
...{
set ...{ _destFile = value; }
get ...{ return _destFile; }
}
/**//// <summary>
/// 目标文件 文件夹
/// </summary>
public string DestFolder
...{
set ...{ _destFolder = value; }
get ...{ return _destFolder; }
}
/**//// <summary>
/// 备份花费时间
/// </summary>
public double UsedTime
...{
set ...{ _usedTime = value; }
get ...{ return _usedTime; }
}
/**//// <summary>
/// 下载路径
/// </summary>
public string DLPath
...{
set ...{ _dlpath = value; }
get ...{ return _dlpath; }
}
/**//// <summary>
/// 创建者
/// </summary>
public string CreatedUser
...{
set ...{ _createdUser = value; }
get ...{ return _createdUser; }
}
public CBackup()
...{ }
}
}
DBHelper.cs
using
System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace BackupTool
... {
/**//// <summary>
/// 数据层操作
/// </summary>
class DBHelper
...{
/**//// <summary>
/// 获取连接对象
/// </summary>
/// <param name="connString"></param>
/// <returns></returns>
public static SqlConnection GetConnection(string connString)
...{
SqlConnection conn = new SqlConnection(connString);
return conn;
}
/**//// <summary>
/// 备份数据库
/// </summary>
/// <param name="conn"></param>
/// <param name="bakname"></param>
/// <param name="bakpath"></param>
/// <param name="dbname"></param>
/// <returns></returns>
public static bool BackDB(SqlConnection conn, string bakname, string bakpath,string dbname)
...{
bool bl = true;
string filepath = bakpath + bakname;
string sql = "exec sp_addumpdevice 'disk'," + "'" + bakname + "','" + filepath + "' backup database "+dbname+" to " + bakname;
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
try
...{
conn.Open();
cmd.ExecuteNonQuery();
bl = bl && true;
cmd.CommandText = "P_CheckBakFile";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@filename", SqlDbType.VarChar, 200));
cmd.Parameters["@filename"].Value = bakname;
cmd.Parameters.Add(new SqlParameter("@filepath", SqlDbType.VarChar, 200));
cmd.Parameters["@filepath"].Value = filepath;
cmd.Parameters.Add(new SqlParameter("@rv", SqlDbType.Int));
cmd.Parameters["@rv"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
int icnt = (int)cmd.Parameters["@rv"].Value;
bl = bl && icnt > 0 ? true : false;
}
catch (Exception ex)
...{
Common.WriteLog(ex);
throw ex;
}
finally
...{
cmd.Dispose();
conn.Close();
}
return bl;
}
/**//// <summary>
/// 获取等待备份文件
/// </summary>
/// <param name="conn"></param>
/// <returns></returns>
public static CBackup[] GetCurrBackup(SqlConnection conn)
...{
string sql = "Select * from TBackup Where Status=1 order by pkid";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
int icnt = da.Fill(ds, "TBackup");
CBackup cb = null;
CBackup[] cbs = null;
int i = 0;
if (icnt > 0)
...{
cbs = new CBackup[icnt];
foreach (DataRow row in ds.Tables["TBackup"].Rows)
...{
cb = new CBackup();
cb.Pkid = Convert.ToInt32(row["PKID"]);
cb.Name = row["Name"].ToString();
cb.CreatedDate = Convert.ToDateTime(row["CreatedDate"]);
cb.Type = Convert.ToInt32(row["Type"]);
cb.Status = Convert.ToInt32(row["Status"]);
cb.DBName = row["DBName"].ToString();
cb.SourceFile = row["SourceFile"].ToString();
cb.DestFile = row["DestFile"].ToString();
cb.DestFolder = row["DestFolder"].ToString();
cb.UsedTime =Convert.ToInt32(row["UsedTime"]);
cb.DLPath = row["DLPath"].ToString();
cb.CreatedUser = row["CreatedUser"].ToString();
cbs[i] = cb;
++i;
}
}
conn.Dispose();
return cbs;
}
/**//// <summary>
/// 更新备份状态
/// </summary>
/// <param name="conn"></param>
/// <param name="cbk"></param>
/// <returns></returns>
public static bool UpdateStatus(SqlConnection conn, CBackup cbk)
...{
/**//*
* Proc P_UpdateBackup
@PKID int,
@Status tinyint,
@UsedTime int,
@DLPath varchar(100),
@rv int output
*/
bool rv = false;
SqlCommand cmd = new SqlCommand("P_UpdateBackup", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@PKID", SqlDbType.Int));
cmd.Parameters["@PKID"].Value = cbk.Pkid;
cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.Int));
cmd.Parameters["@Status"].Value = cbk.Status;
cmd.Parameters.Add(new SqlParameter("@UsedTime", SqlDbType.Float));
cmd.Parameters["@UsedTime"].Value = cbk.UsedTime;
cmd.Parameters.Add(new SqlParameter("@DLPath", SqlDbType.VarChar, 100));
cmd.Parameters["@DLPath"].Value = cbk.DLPath;
cmd.Parameters.Add(new SqlParameter("@rv", SqlDbType.Int));
cmd.Parameters["@rv"].Direction = ParameterDirection.Output;
try
...{
conn.Open();
cmd.ExecuteNonQuery();
int icnt = (int)cmd.Parameters["@rv"].Value;
if (icnt > 0)
rv = true;
else
rv = false;
}
catch (Exception ex)
...{
Common.WriteLog(ex);
throw ex;
}
finally
...{
cmd.Dispose();
conn.Close();
}
return rv;
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace BackupTool
... {
/**//// <summary>
/// 数据层操作
/// </summary>
class DBHelper
...{
/**//// <summary>
/// 获取连接对象
/// </summary>
/// <param name="connString"></param>
/// <returns></returns>
public static SqlConnection GetConnection(string connString)
...{
SqlConnection conn = new SqlConnection(connString);
return conn;
}
/**//// <summary>
/// 备份数据库
/// </summary>
/// <param name="conn"></param>
/// <param name="bakname"></param>
/// <param name="bakpath"></param>
/// <param name="dbname"></param>
/// <returns></returns>
public static bool BackDB(SqlConnection conn, string bakname, string bakpath,string dbname)
...{
bool bl = true;
string filepath = bakpath + bakname;
string sql = "exec sp_addumpdevice 'disk'," + "'" + bakname + "','" + filepath + "' backup database "+dbname+" to " + bakname;
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
try
...{
conn.Open();
cmd.ExecuteNonQuery();
bl = bl && true;
cmd.CommandText = "P_CheckBakFile";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@filename", SqlDbType.VarChar, 200));
cmd.Parameters["@filename"].Value = bakname;
cmd.Parameters.Add(new SqlParameter("@filepath", SqlDbType.VarChar, 200));
cmd.Parameters["@filepath"].Value = filepath;
cmd.Parameters.Add(new SqlParameter("@rv", SqlDbType.Int));
cmd.Parameters["@rv"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
int icnt = (int)cmd.Parameters["@rv"].Value;
bl = bl && icnt > 0 ? true : false;
}
catch (Exception ex)
...{
Common.WriteLog(ex);
throw ex;
}
finally
...{
cmd.Dispose();
conn.Close();
}
return bl;
}
/**//// <summary>
/// 获取等待备份文件
/// </summary>
/// <param name="conn"></param>
/// <returns></returns>
public static CBackup[] GetCurrBackup(SqlConnection conn)
...{
string sql = "Select * from TBackup Where Status=1 order by pkid";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
int icnt = da.Fill(ds, "TBackup");
CBackup cb = null;
CBackup[] cbs = null;
int i = 0;
if (icnt > 0)
...{
cbs = new CBackup[icnt];
foreach (DataRow row in ds.Tables["TBackup"].Rows)
...{
cb = new CBackup();
cb.Pkid = Convert.ToInt32(row["PKID"]);
cb.Name = row["Name"].ToString();
cb.CreatedDate = Convert.ToDateTime(row["CreatedDate"]);
cb.Type = Convert.ToInt32(row["Type"]);
cb.Status = Convert.ToInt32(row["Status"]);
cb.DBName = row["DBName"].ToString();
cb.SourceFile = row["SourceFile"].ToString();
cb.DestFile = row["DestFile"].ToString();
cb.DestFolder = row["DestFolder"].ToString();
cb.UsedTime =Convert.ToInt32(row["UsedTime"]);
cb.DLPath = row["DLPath"].ToString();
cb.CreatedUser = row["CreatedUser"].ToString();
cbs[i] = cb;
++i;
}
}
conn.Dispose();
return cbs;
}
/**//// <summary>
/// 更新备份状态
/// </summary>
/// <param name="conn"></param>
/// <param name="cbk"></param>
/// <returns></returns>
public static bool UpdateStatus(SqlConnection conn, CBackup cbk)
...{
/**//*
* Proc P_UpdateBackup
@PKID int,
@Status tinyint,
@UsedTime int,
@DLPath varchar(100),
@rv int output
*/
bool rv = false;
SqlCommand cmd = new SqlCommand("P_UpdateBackup", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@PKID", SqlDbType.Int));
cmd.Parameters["@PKID"].Value = cbk.Pkid;
cmd.Parameters.Add(new SqlParameter("@Status", SqlDbType.Int));
cmd.Parameters["@Status"].Value = cbk.Status;
cmd.Parameters.Add(new SqlParameter("@UsedTime", SqlDbType.Float));
cmd.Parameters["@UsedTime"].Value = cbk.UsedTime;
cmd.Parameters.Add(new SqlParameter("@DLPath", SqlDbType.VarChar, 100));
cmd.Parameters["@DLPath"].Value = cbk.DLPath;
cmd.Parameters.Add(new SqlParameter("@rv", SqlDbType.Int));
cmd.Parameters["@rv"].Direction = ParameterDirection.Output;
try
...{
conn.Open();
cmd.ExecuteNonQuery();
int icnt = (int)cmd.Parameters["@rv"].Value;
if (icnt > 0)
rv = true;
else
rv = false;
}
catch (Exception ex)
...{
Common.WriteLog(ex);
throw ex;
}
finally
...{
cmd.Dispose();
conn.Close();
}
return rv;
}
}
}
CThread.cs
using
System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
namespace BackupTool
... {
class CThread
...{
事件#region 事件
//定义委托
public delegate void CThreadEventHandler(CThreadEventArgs e);
//定义事件
public static event CThreadEventHandler CThreadChange;
//事件调用
public static void OnCThreadChange(CThreadEventArgs e)
...{
if (CThreadChange != null)
CThreadChange(e);
}
public class CThreadEventArgs : EventArgs
...{
public string message;
public string flag;
public CThreadEventArgs()
...{
}
public CThreadEventArgs(string message, string flag)
...{
this.message = message;
this.flag = flag;
}
}
#endregion
private ThreadStart ts;
private Thread t;
private bool iscon = true; //线程循环条件
public CThread()
...{
}
public void Start()
...{
iscon = true;
ts = new ThreadStart(this.Do);
t = new Thread(ts);
try
...{
t.Start();
}
catch (Exception e)
...{
Common.WriteLog(e);
t.Abort();
}
}
/**//// <summary>
/// 线程运行调用方法
/// </summary>
private void Do()
...{
CThreadEventArgs cea = null;
SqlConnection conn;
try
...{
while (iscon)
...{
//获取当前数据库连接
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
CBackup[] cbs = DBHelper.GetCurrBackup(conn);
conn = null;
if (cbs != null)
...{
for (int i = 0; i < cbs.Length; i++)
...{
//初始 等待中
cea = new CThreadEventArgs(_CombineMsg(cbs[i]), "");
OnCThreadChange(cea);
//更改状态为备份中
cbs[i].Status = 2;
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
//开始备份
if (cbs[i].Type == 1) //备份图片等文件
...{
try
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 开始备份文件... ";
OnCThreadChange(cea);
DateTime dtnow = System.DateTime.Now;
bool bl = ZipHelper.Compress(cbs[i].SourceFile, cbs[i].DestFolder + cbs[i].DestFile +".zip",true);
System.TimeSpan tsp = System.DateTime.Now.Subtract(dtnow);
if (bl == true)
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "文件备份完成,耗时(秒):" + tsp.TotalSeconds.ToString();
OnCThreadChange(cea);
cbs[i].Status = 3; //更改状态为备份完成
cbs[i].UsedTime = tsp.TotalSeconds;
cbs[i].DLPath = Common.CON_DOWNLOAD_PATH + cbs[i].DBName + cbs[i].DestFile +".zip";
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
else
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "文件备份失败,耗时(秒):" + tsp.TotalSeconds.ToString();
OnCThreadChange(cea);
cbs[i].Status = 4; //更改状态为备份失败
cbs[i].UsedTime = tsp.TotalSeconds;
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
}
catch (Exception exz)
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[0].Pkid.ToString() + "文件备份出错,错误信息:" + exz.Message;
OnCThreadChange(cea);
cbs[i].Status = 4; //更改状态为备份失败
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
finally
...{ }
}
else //备份数据库
...{
try
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 开始备份数据库... ";
OnCThreadChange(cea);
DateTime dtnow = System.DateTime.Now;
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
bool bl = DBHelper.BackDB(conn, cbs[i].DestFile, cbs[i].DestFolder, cbs[i].DBName);
if (bl == true)
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "数据库备份完成...";
OnCThreadChange(cea);
//进行压缩
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "正在压缩数据库备份...";
OnCThreadChange(cea);
string bakfilepath = cbs[i].DestFolder + cbs[i].DestFile;
string baktagfilepaht = cbs[i].DestFolder + cbs[i].DestFile + ".zip";
string[] strs = ...{ bakfilepath };
ZipHelper.Compress(strs, baktagfilepaht);
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "压缩数据库备份完成...";
OnCThreadChange(cea);
//删除原bak文件
if (File.Exists(bakfilepath))
File.Delete(bakfilepath);
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "删除原数据库备份完成...";
OnCThreadChange(cea);
//计时
System.TimeSpan tsp = System.DateTime.Now.Subtract(dtnow);
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "数据库备份全部完成,耗时(秒):" + tsp.TotalSeconds.ToString();
OnCThreadChange(cea);
cbs[i].Status = 3; //更改状态为备份完成
cbs[i].UsedTime = tsp.TotalSeconds;
cbs[i].DLPath = Common.CON_DOWNLOAD_PATH + cbs[i].DBName + cbs[i].DestFile + ".zip";
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
else
...{
System.TimeSpan tsp = System.DateTime.Now.Subtract(dtnow);
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "数据库备份失败,耗时(秒):" + tsp.TotalSeconds.ToString();
OnCThreadChange(cea);
cbs[i].Status = 4; //更改状态为备份失败
cbs[i].UsedTime = tsp.TotalSeconds;
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
}
catch (Exception exz)
...{
Common.WriteLog(exz);
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[0].Pkid.ToString() + "数据库备份出错,错误信息:" + exz.Message;
OnCThreadChange(cea);
cbs[i].Status = 4; //更改状态为备份失败
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
finally
...{ }
}
}
}
Thread.Sleep(10000);
}
}
catch (Exception ex)
...{
cea = new CThreadEventArgs("出现异常:" + ex.Message, "");
OnCThreadChange(cea);
Common.WriteLog(ex);
}
finally
...{ }
}
/**//// <summary>
/// 终止线程
/// </summary>
public void Stop()
...{
this.iscon = false;
Common.WriteLog("testing over");
}
/**//// <summary>
/// 组合信息
/// </summary>
/// <param name="cbk"></param>
/// <returns></returns>
private string _CombineMsg(CBackup cbk)
...{
string rv = " ================================================================";
rv = rv + " 编号:" + cbk.Pkid.ToString();
rv = rv + " 名称:" + cbk.Name;
rv = rv + " 创建时间:" + cbk.CreatedDate.ToString();
rv = rv + " 创建者:" + cbk.CreatedUser;
rv = rv + " 项目:" + cbk.DBName;
if ( cbk.Type == 1)
rv = rv + " 备份类型:" + "文件备份";
else
rv = rv + " 备份类型:" + "数据库备份";
rv = rv + " 源文件:" + cbk.SourceFile;
rv = rv + " 目标文件:" + cbk.DestFile;
rv = rv + " 目标文件夹:" + cbk.DestFolder;
rv = rv + " 状态:" + _ParseStatus(cbk.Status);
rv = rv + " ";
return rv;
}
/**//// <summary>
/// 获取备份状态
/// </summary>
/// <param name="status"></param>
/// <returns></returns>
private string _ParseStatus(int status)
...{
string rv = "";
switch (status)
...{
case 1:
rv = "等待中";
break;
case 2:
rv = "备份中";
break;
case 3:
rv = "备份完成";
break;
case 4:
rv = "备份失败";
break;
}
return rv;
}
}
}
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
namespace BackupTool
... {
class CThread
...{
事件#region 事件
//定义委托
public delegate void CThreadEventHandler(CThreadEventArgs e);
//定义事件
public static event CThreadEventHandler CThreadChange;
//事件调用
public static void OnCThreadChange(CThreadEventArgs e)
...{
if (CThreadChange != null)
CThreadChange(e);
}
public class CThreadEventArgs : EventArgs
...{
public string message;
public string flag;
public CThreadEventArgs()
...{
}
public CThreadEventArgs(string message, string flag)
...{
this.message = message;
this.flag = flag;
}
}
#endregion
private ThreadStart ts;
private Thread t;
private bool iscon = true; //线程循环条件
public CThread()
...{
}
public void Start()
...{
iscon = true;
ts = new ThreadStart(this.Do);
t = new Thread(ts);
try
...{
t.Start();
}
catch (Exception e)
...{
Common.WriteLog(e);
t.Abort();
}
}
/**//// <summary>
/// 线程运行调用方法
/// </summary>
private void Do()
...{
CThreadEventArgs cea = null;
SqlConnection conn;
try
...{
while (iscon)
...{
//获取当前数据库连接
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
CBackup[] cbs = DBHelper.GetCurrBackup(conn);
conn = null;
if (cbs != null)
...{
for (int i = 0; i < cbs.Length; i++)
...{
//初始 等待中
cea = new CThreadEventArgs(_CombineMsg(cbs[i]), "");
OnCThreadChange(cea);
//更改状态为备份中
cbs[i].Status = 2;
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
//开始备份
if (cbs[i].Type == 1) //备份图片等文件
...{
try
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 开始备份文件... ";
OnCThreadChange(cea);
DateTime dtnow = System.DateTime.Now;
bool bl = ZipHelper.Compress(cbs[i].SourceFile, cbs[i].DestFolder + cbs[i].DestFile +".zip",true);
System.TimeSpan tsp = System.DateTime.Now.Subtract(dtnow);
if (bl == true)
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "文件备份完成,耗时(秒):" + tsp.TotalSeconds.ToString();
OnCThreadChange(cea);
cbs[i].Status = 3; //更改状态为备份完成
cbs[i].UsedTime = tsp.TotalSeconds;
cbs[i].DLPath = Common.CON_DOWNLOAD_PATH + cbs[i].DBName + cbs[i].DestFile +".zip";
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
else
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "文件备份失败,耗时(秒):" + tsp.TotalSeconds.ToString();
OnCThreadChange(cea);
cbs[i].Status = 4; //更改状态为备份失败
cbs[i].UsedTime = tsp.TotalSeconds;
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
}
catch (Exception exz)
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[0].Pkid.ToString() + "文件备份出错,错误信息:" + exz.Message;
OnCThreadChange(cea);
cbs[i].Status = 4; //更改状态为备份失败
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
finally
...{ }
}
else //备份数据库
...{
try
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 开始备份数据库... ";
OnCThreadChange(cea);
DateTime dtnow = System.DateTime.Now;
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
bool bl = DBHelper.BackDB(conn, cbs[i].DestFile, cbs[i].DestFolder, cbs[i].DBName);
if (bl == true)
...{
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "数据库备份完成...";
OnCThreadChange(cea);
//进行压缩
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "正在压缩数据库备份...";
OnCThreadChange(cea);
string bakfilepath = cbs[i].DestFolder + cbs[i].DestFile;
string baktagfilepaht = cbs[i].DestFolder + cbs[i].DestFile + ".zip";
string[] strs = ...{ bakfilepath };
ZipHelper.Compress(strs, baktagfilepaht);
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "压缩数据库备份完成...";
OnCThreadChange(cea);
//删除原bak文件
if (File.Exists(bakfilepath))
File.Delete(bakfilepath);
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "删除原数据库备份完成...";
OnCThreadChange(cea);
//计时
System.TimeSpan tsp = System.DateTime.Now.Subtract(dtnow);
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "数据库备份全部完成,耗时(秒):" + tsp.TotalSeconds.ToString();
OnCThreadChange(cea);
cbs[i].Status = 3; //更改状态为备份完成
cbs[i].UsedTime = tsp.TotalSeconds;
cbs[i].DLPath = Common.CON_DOWNLOAD_PATH + cbs[i].DBName + cbs[i].DestFile + ".zip";
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
else
...{
System.TimeSpan tsp = System.DateTime.Now.Subtract(dtnow);
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[i].Pkid.ToString() + "数据库备份失败,耗时(秒):" + tsp.TotalSeconds.ToString();
OnCThreadChange(cea);
cbs[i].Status = 4; //更改状态为备份失败
cbs[i].UsedTime = tsp.TotalSeconds;
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
}
catch (Exception exz)
...{
Common.WriteLog(exz);
cea.message = "[" + System.DateTime.Now.ToString() + "] 编号" + cbs[0].Pkid.ToString() + "数据库备份出错,错误信息:" + exz.Message;
OnCThreadChange(cea);
cbs[i].Status = 4; //更改状态为备份失败
conn = DBHelper.GetConnection(Common.CON_CONNSTR);
DBHelper.UpdateStatus(conn, cbs[i]);
cea.message = " ================================================================";
OnCThreadChange(cea);
}
finally
...{ }
}
}
}
Thread.Sleep(10000);
}
}
catch (Exception ex)
...{
cea = new CThreadEventArgs("出现异常:" + ex.Message, "");
OnCThreadChange(cea);
Common.WriteLog(ex);
}
finally
...{ }
}
/**//// <summary>
/// 终止线程
/// </summary>
public void Stop()
...{
this.iscon = false;
Common.WriteLog("testing over");
}
/**//// <summary>
/// 组合信息
/// </summary>
/// <param name="cbk"></param>
/// <returns></returns>
private string _CombineMsg(CBackup cbk)
...{
string rv = " ================================================================";
rv = rv + " 编号:" + cbk.Pkid.ToString();
rv = rv + " 名称:" + cbk.Name;
rv = rv + " 创建时间:" + cbk.CreatedDate.ToString();
rv = rv + " 创建者:" + cbk.CreatedUser;
rv = rv + " 项目:" + cbk.DBName;
if ( cbk.Type == 1)
rv = rv + " 备份类型:" + "文件备份";
else
rv = rv + " 备份类型:" + "数据库备份";
rv = rv + " 源文件:" + cbk.SourceFile;
rv = rv + " 目标文件:" + cbk.DestFile;
rv = rv + " 目标文件夹:" + cbk.DestFolder;
rv = rv + " 状态:" + _ParseStatus(cbk.Status);
rv = rv + " ";
return rv;
}
/**//// <summary>
/// 获取备份状态
/// </summary>
/// <param name="status"></param>
/// <returns></returns>
private string _ParseStatus(int status)
...{
string rv = "";
switch (status)
...{
case 1:
rv = "等待中";
break;
case 2:
rv = "备份中";
break;
case 3:
rv = "备份完成";
break;
case 4:
rv = "备份失败";
break;
}
return rv;
}
}
}
Program.cs
using
System;
using System.Collections.Generic;
using System.Text;
namespace BackupTool
... {
class Program
...{
static void Main(string[] args)
...{
CThread cth = new CThread();
BackupTool.CThread.CThreadChange += new CThread.CThreadEventHandler(WriteCTheadMsg);
Output("[" + System.DateTime.Now.ToString() + "] 备份服务开始...");
cth.Start();
}
public static void WriteCTheadMsg(BackupTool.CThread.CThreadEventArgs e)
...{
Output(e.message);
}
static void Output(String str)
...{
System.Console.WriteLine(str);
}
}
}
using System.Collections.Generic;
using System.Text;
namespace BackupTool
... {
class Program
...{
static void Main(string[] args)
...{
CThread cth = new CThread();
BackupTool.CThread.CThreadChange += new CThread.CThreadEventHandler(WriteCTheadMsg);
Output("[" + System.DateTime.Now.ToString() + "] 备份服务开始...");
cth.Start();
}
public static void WriteCTheadMsg(BackupTool.CThread.CThreadEventArgs e)
...{
Output(e.message);
}
static void Output(String str)
...{
System.Console.WriteLine(str);
}
}
}