首页 > 代码库 > 自动备份SQL数据库 并删除指定日期之前的备份文件

自动备份SQL数据库 并删除指定日期之前的备份文件

/// <summary>
        /// 数据备份
        /// </summary>
        ///

        public bool DataBackup(string getpath)
        {
            try
            {
                SqlConnection con = new SqlConnection();  //利用代码实现连接数据库

                con.ConnectionString = ConfigurationSettings.AppSettings["DataBase"].ToString();
                con.Open();
                SqlCommand com = new SqlCommand();
                com.CommandText = "BACKUP DATABASE Name TO DISK = ‘" + getpath + "‘";
                com.Connection = con;       //连接
                com.ExecuteNonQuery();

                //int i = com.ExecuteNonQuery();
                //if (com.ExecuteNonQuery() ==-1)
                //{
                //    ShowExclamation("数据已成功备份!");
                //}            
                con.Close();
                con.Dispose();
                return true;
            }
            catch (Exception k)
            {
                //MessageBox.Show(k.Message);
                return false;
            }
        }

 

if (!System.IO.Directory.Exists("D:\\备份文件"))
                {
                    System.IO.Directory.CreateDirectory("D:\\备份文件");
                }
                string path = @"D:\备份文件\" +  DateTime.Now.ToString("yyyyMMddHHmmss") + ".bak ";
                this.dqlib.DataBackup(path);
                DirectoryInfo baseDir = new DirectoryInfo("D:\\备份文件");
                // 获取指定文件夹下的所有文件。
                // 如果你需要获取特定格式的文件,如.html 结尾的,可以写成 baseDir.GetFiles("*.html");
                FileInfo[] files = baseDir.GetFiles();

                // 定义文件名字符串
                string fileNames = string.Empty;

                if (files.Length > 10)
                {
                    for (int i = 0; i < files.Length; i++)
                    {
                        // 获取每个文件名,并记录到 字符串 fileNames 里
                        // 如果需要获取文件的完整路径名, files[i].FullName;
                        if (DateTime.Compare(files[i].CreationTime, DateTime.Now.AddDays(-10)) < 0)
                        {
                            files[i].Delete();
                        }

                    }
                }

自动备份SQL数据库 并删除指定日期之前的备份文件