Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have an appliaction in c#. & I am using SQL server 2005. I stored the database in bin\debug\App_Data folder.

I want to get the back of my database when I click on backup_button. & restore the database in given location when click on restore_button.

Thanks in advance.
Posted

Hi,

Try this for backup:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlClient;
namespace Utilities
{
    public class Backup
    {
        public virtual bool MyFile(string targetSavePath, string catalogDb, string bConnToBackup)
        {
            //Author: Algem Mojedo
            bool retValue = false;
            DirectoryInfo dirInfo = new DirectoryInfo(targetSavePath);
            if (!dirInfo.Exists)
            {
                return retValue;
            }
            string todayIs = DateTime.Today.ToShortDateString().Trim().Replace("/", "-") + ".bak";
            StringBuilder sb = new StringBuilder();
            sb.Append(" USE MASTER " + "\r\n ");
            sb.Append(" DECLARE @fileName VARCHAR(50) " + "\r\n ");
            sb.Append(" DECLARE @fileDate VARCHAR(20)  " + "\r\n  ");
            sb.Append(" DECLARE @path VARCHAR(220)  " + "\r\n  ");
            sb.Append("\r\n ");
            sb.Append(" SET @path =  '" + targetSavePath + "'\r\n ");
            sb.Append(" SET @fileName = '" + catalogDb + "'\r\n ");
            sb.Append(" SELECT @fileDate = CONVERT(VARCHAR(20), GETDATE(),112) " + "\r\n "); //-- Fetching today's data
            sb.Append(" DECLARE db_cursor CURSOR FOR " + "\r\n ");
            sb.Append(" SELECT name FROM dbo.sysdatabases WHERE name IN ('" + catalogDb + "') " + "\r\n ");
            sb.Append(" OPEN db_cursor   FETCH NEXT FROM db_cursor INTO @fileDate " + "\r\n ");
            sb.Append(" WHILE @@FETCH_STATUS = 0   BEGIN  " + "\r\n ");
            sb.Append(" SET @fileName = @path + @fileDate + '_" + todayIs + "' \r\n ");
            sb.Append(" BACKUP DATABASE @fileDate TO DISK = @fileName " + "\r\n ");
            sb.Append(" FETCH NEXT FROM db_cursor INTO @fileDate  END " + "\r\n ");
            sb.Append(" CLOSE db_cursor   DEALLOCATE db_cursor " + "\r\n ");
            string sbStr = sb.ToString();
            string adCon = string.Empty;
            if (!(bConnToBackup.ToLower().Contains("timeout")))
            {
                adCon = ";Connect Timeout=300; pooling='true'; Max Pool Size=300";
            }
            SqlConnection conn = new SqlConnection((bConnToBackup + adCon));
            SqlCommand cmd = new SqlCommand(sbStr);
            try
            {
                cmd.Connection = conn;
                cmd.Connection.Open();
                cmd.CommandTimeout = 300;
                cmd.ExecuteScalar();
                retValue = true;
            }
            catch (Exception)
            {
                retValue = false;
                return retValue;
            }
            finally
            {
                cmd.Dispose();
                conn.Close();
            }
            return retValue;
        }
    }
}


Remember to vote on this if help...

Regards,

Algem
 
Share this answer
 
Comments
deepakjagd 4-Oct-11 0:50am    
Thanks...

I run this code. It run successfully, but target folder is blank/empty.

I give the targetSave Path = "F:\\App_Data" & catLogDB = "TestDB.mdf" & connTobackup file is "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + path + ;Integrated Security=True;User Instance=True"

here string path = strStartupPath + "\\App_Data\\TestDB.mdf"


Is it correct?
Al Moje 4-Oct-11 2:06am    
Hi,
If your targetSavePath = "f:\App_Data", the App_Data sub directory should be existing.
I only use to specify as example:
targetSavePath= "f:\"
catalogDb = "Payroll"
bConnToBackup = [MyConnectionString]

Example in you Web.Config:
<add name="MyConnectionString" connectionstring="Data Source=.;Initial Catalog=Payroll;Integrated Security=True">

if (!(bConnToBackup.ToLower().Contains("timeout")))
{
adCon = ";Connect Timeout=300; pooling='true'; Max Pool Size=300";
}
SqlConnection conn = new SqlConnection((bConnToBackup + adCon));

In above my statement the connection that I had defined does not content TimeOut
so I modify my connection and add the
";Connect Timeout=300; pooling='true'; Max Pool Size=300"
so that the connection timeout will be extend to 300 and also note
that the cmd.CommandTimeout = 300.

the Connection timeout and the CommandTimeout should be fair as shown set to 300.
cause sometimes backup take too long... You could increase the time out depend on needs.
Al Moje 4-Oct-11 2:13am    
Example of ConnectioString:
<connectionstrings>
<add name="MyConnectionString" connectionstring="Data Source=.;Initial Catalog=Payroll;Integrated Security=True">
deepakjagd 4-Oct-11 3:09am    
Hi,

It not works. the database not copied in the targetsavefile only the application run successfully.
Please late me know where i am doing the mistake?
Al Moje 4-Oct-11 4:10am    
Hi,

Change the
targetSavePath= ".\\"

Note that the backup will be copy to your machine at:
C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup
 
Share this answer
 
This is for backup
C#
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Windows.Forms;
using System.IO;
using System.Collections.Generic;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common; 
     
  {
            SaveFileDialog saveFileDlg = new SaveFileDialog();
            saveFileDlg.Filter = "Mircosoft Access Files(*.mdb)|*.mdb";
            saveFileDlg.Title = "Create Invoice Backup";
            saveFileDlg.RestoreDirectory = false;
            if (saveFileDlg.ShowDialog() == DialogResult.OK)
            {

                string sourceFile = Application.StartupPath.ToString() + "\\InvoiceGenerator.mdb";

                string DatabaseName = saveFileDlg.FileName;
                string img = "Images";
                string sourcePath = (Application.StartupPath + "/Images/");
                string targetPath = DatabaseName.Replace(DatabaseName, img);
                try
                {
                    File.Copy(sourceFile, DatabaseName);
                    MessageBox.Show("Backup Create Successfully");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                }

                if (System.IO.Directory.Exists(sourcePath))
                {
                    string[] files = System.IO.Directory.GetFiles(sourcePath);
                    string fileName;
                    string destFile;
                    foreach (string s in files)
                    {
                        fileName = System.IO.Path.GetFileName(s);
                        destFile = System.IO.Path.Combine(targetPath, fileName);
                        System.IO.File.Copy(s, destFile, true);
                    }
                }
                else
                {
                    MessageBox.Show("Source path does not exist!");
                }


            }
        }


//..................THis Is For Restore.........................

        {
            string message = "After Restoring the Database from a previous Backup, Current Database will be lost and the changes made after Backup will become unrecoverable. Are you sure you want to Continue!";
            string caption = "Restore Backup";
            DialogResult result;
            string img;
            img = AppDomain.CurrentDomain.BaseDirectory + "database_add_48.png";

            //MessageBox.Show(message, caption, MessageBoxButtons.YesNo);
            result = MessageBox.Show(message, caption, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);

            if (result == DialogResult.Yes)
            {

                OpenFileDialog openDlg = new OpenFileDialog();
                openDlg.Filter = "DataBase Files (*.mdb)|*.mdb";
                openDlg.FileName = "";
                openDlg.DefaultExt = ".mdb";
                openDlg.CheckFileExists = true;
                openDlg.CheckPathExists = true;
                DialogResult res = openDlg.ShowDialog();
                if (res == DialogResult.OK)
                {
                    if (!(openDlg.FileName).EndsWith(".mdb") && !(openDlg.FileName).EndsWith(".MDB"))
                        MessageBox.Show("Invalid file format...!", "Prajeesh", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    else
                    {
                        string sourceFile = Application.StartupPath.ToString() + "\\InvoiceGenerator.mdb";

                        string DatabaseName = openDlg.FileName;
                        try
                        {
                            //File.Delete(sourceFile);
                            // File.Copy(DatabaseName, sourceFile);


                            File.Copy(DatabaseName, sourceFile, true);


                            MessageBox.Show("Restore Successfully");
                            // pictureBox3.ImageLocation = img;
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }

                    }
                }

            }
        }
 
Share this answer
 
v2
Comments
yahya_ 16-Apr-12 0:19am    
hii have error below running
The process cannot access file "my database path" because it is being used by another process.
please help me

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900