//声明临时数据库名称
string temp = DateTime.Now.Year.ToString();
temp += DateTime.Now.Month.ToString();
temp += DateTime.Now.Day.ToString();
temp += DateTime.Now.Hour.ToString();
temp += DateTime.Now.Minute.ToString();
temp += DateTime.Now.Second.ToString() + ".bak";
temp = DBPath.Substring(0, DBPath.LastIndexOf("\\") + 1) + temp;
//定义临时数据库的连接字符串
string temp2 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+temp;
//定义目标数据库的连接字符串
string DBPath2 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+DBPath;
//创建一个JetEngineClass对象的实例
JRO.JetEngineClass jt = new JRO.JetEngineClass();
//使用JetEngineClass对象的CompactDatabase方法压缩修复数据库
jt.CompactDatabase(DBPath2, temp2);
//拷贝临时数据库到目标数据库(覆盖)
File.Copy(temp, DBPath, true);
//最后删除临时数据库
File.Delete(temp);
}
#endregion
#region 备份Access数据库
/// <summary>
/// 备份Access数据库
/// </summary>
/// <param name="srcPath">要备份的数据库绝对路径</param>
/// <param name="aimPath">备份到的数据库绝对路径</param>
/// <returns></returns>
public static void Backup(string srcPath,string aimPath)
{
if (!File.Exists(srcPath))
{
throw new Exception("源数据库不存在,无法备份");
}
try
{
File.Copy(srcPath,aimPath,true);
}
catch(IOException ixp)
{
throw new Exception(ixp.ToString());
}
}
#endregion
#region 还原Access数据库
/// <summary>
/// 还原Access数据库
/// </summary>
/// <param name="bakPath">备份的数据库绝对路径</param>
/// <param name="dbPath">要还原的数据库绝对路径</param>
public static void RecoverAccess(string bakPath,string dbPath)
{
if (!File.Exists(bakPath))
{
throw new Exception("备份数据库不存在,无法还原");
}
try
{
File.Copy(bakPath, dbPath, true);
}
catch (IOException ixp)
{
throw new Exception(ixp.ToString());
}
}
#endregion
}
}