Click here to Skip to main content
16,012,082 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a problem in below code debug correctely but not create backup and restore
when we click on backup button then computer restart and not create backup files in destination folder plz help me..
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.IO;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace Crime_System
{
    public partial class Backup_files : Form
    {
         public int controller = 0;
         public static Backup_files Bup;
         public Backup_files()
    {
            InitializeComponent();
        }
          
           public void restart(string msg)
         {
             if (controller == 0)
             {
                 if (Get_MSG_PAID(msg) == "yes")
                 {

                     FileStream fs = File.OpenWrite("backup.txt");
                     string s = "backup";

                     byte[] data = new byte[s.Length];
                     data = Encoding.ASCII.GetBytes(s);
                     fs.Write(data, 0, s.Length);
                     fs.Close();
                     System.Diagnostics.Process.Start("ShutDown", "/r");
                 }
             }
         }
         public string Get_MSG_PAID(string message)
         {
             // string message = "Are you sure to save ";
             string caption = "Back Up Confirmation.......";
             MessageBoxButtons buttons = MessageBoxButtons.YesNo;
             MessageBoxIcon icon = MessageBoxIcon.Question;
             //   buttons = MessageBoxButtons.OK;
             DialogResult result;


             // Displays the MessageBox.

             result = MessageBox.Show(message, caption, buttons, icon);

             //  System.Windows.Forms.DialogResult..Abort;

             if (result == System.Windows.Forms.DialogResult.Yes)
             {
                 return "yes";
             }
             else
             {
                 return "no";
             }
         }

         public static void Get_Control()
         {
             Bup = new Backup_files();
             Bup.ShowDialog();
         }
         public void ManualFileRestoration(string target)
         {
             try
             {
                 string path = "";
                 string path2 = "";
                 //FileStream fs = File.OpenWrite("dirinfo.txt");
                 // StreamWriter sfr = new StreamWriter(fs);
                 string subpath = @"c:\users\khan\documents\visual studio 2010\Projects\Crime System\Crime System\Database1.mdf";
                 string subpath2 = @"C:\Users\khan\Documents\Visual Studio 2010\Projects\Crime System\Crime System\Database1_log.ldf";
                 string sh = Directory.GetDirectoryRoot("dirinfo.txt");
                 path = sh + subpath;
                 path2 = sh + subpath2;
                 File.Copy(target + "Database1.mdf", path, true);
                 File.Copy(target + "Database1_log.ldf", path2, true);
                 MessageBox.Show("Back up successfully Restored");
             }
             catch (Exception ee)
             {
                 MessageBox.Show(ee.GetBaseException().ToString());
             }
         }

        private void button2_Click(object sender, EventArgs e)
        {
            if (controller != 0)
            {
                try
                {
                    if (!Directory.Exists(label1.Text))
                    {
                        MessageBox.Show("No Directory is exist");
                        return;
                    }
                    string path = "";
                    string path2 = "";
                    //FileStream fs = File.OpenWrite("dirinfo.txt");
                    // StreamWriter sfr = new StreamWriter(fs);
                    string subpath = @"c:\users\khan\documents\visual studio 2010\Projects\Crime System\Crime System\Database1.mdf";
                    string subpath2 = @"C:\Users\khan\Documents\Visual Studio 2010\Projects\Crime System\Crime System\Database1_log.ldf";
                    string sh = Directory.GetDirectoryRoot("dirinfo.txt");
                    path = sh + subpath;
                    path2 = sh + subpath2;

                    File.Copy(path, label1.Text + "Database1.mdf", true);
                    File.Copy(path2, label1.Text + "Database1_log.ldf", true);
                    MessageBox.Show("Successfuly Created Database Back Up");
                }
                catch (Exception ee)
                {
                    MessageBox.Show("ERROR" + ee.GetBaseException().ToString());
                }
            }
            else
                restart("you must have to restart computer to craate back up \n press ok to restart");
       
        }

        private void button3_Click_1(object sender, EventArgs e)
        {

            if (controller == 0)
            {
                this.Hide();
            }
            else
            {
                access obj = new access();
                //obj.Show();
                this.Hide();
            }
        }

        private void button4_Click_1(object sender, EventArgs e)
        {
            try
            {
                folderBrowserDialog1.ShowDialog().ToString();
                string s = folderBrowserDialog1.SelectedPath;
                string target = s + @"\";

                if (!File.Exists(target + "Database1.mdf"))
                {
                    MessageBox.Show("No data base file found");
                    return;
                }
                else if (!File.Exists(target + "Database1_log.ldf"))
                {
                    MessageBox.Show("No data base file found");
                    return;
                }
                label2.Text = target;

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.GetBaseException().ToString());
            }
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            Hashtable ht = new Hashtable();
            FileStream sfs = new FileStream("temp.xml", FileMode.Open, FileAccess.Read);

            Hashtable h = new Hashtable();
            BinaryFormatter formatter = new BinaryFormatter();
            h = (Hashtable)formatter.Deserialize(sfs);
            string status = Convert.ToString(h["admin"]);
            sfs.Close();
            if (status == "admin")
            {
                if (controller != 0)
                {
                    ManualFileRestoration(label2.Text);
                }
                else
                    restart("you must have to restart computer to restore back up \n press ok to restart");
                      }
            else
            {
                MessageBox.Show("Your are unable to perform this operatoin");

            }
        }

        private void button6_Click_1(object sender, EventArgs e)
        {
            if (controller == 0)
            {
                this.Hide();
            }
            else
            {
                access obj = new access();
                //obj.Show();
                this.Hide();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                folderBrowserDialog1.ShowDialog().ToString();
                string s = folderBrowserDialog1.SelectedPath;
                string target = s + @"\";
                label1.Text = target;
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.GetBaseException().ToString());
            }
        }
 
    }
}


plz help me any body...guide me
Posted
Comments
notjustme 13-Mar-12 15:13pm    
Ops, that was supposed to be a comment/question rather than a solution. I apologize. :)


----

Granted, I'm a beginner so maybe I'm missing something here. However I'm curious about this lil bit of your code;


string subpath = @"c:\users\khan\documents\visual studio 2010\Projects\Crime System\Crime System\Database1.mdf";

string subpath2 = @"C:\Users\khan\Documents\Visual Studio 2010\Projects\Crime System\Crime System\Database1_log.ldf";

string sh = Directory.GetDirectoryRoot("dirinfo.txt");
path = sh + subpath;
path2 = sh + subpath2;


If we assume "dirinfo.txt" is on your C-drive, wouldn't path and path2 become something like "C:\c:\users..."? Like I said though, I'm a beginner so maybe I'm missing something here. Smile | :)

//use for list of database from which we want to restore…


con = new SqlConnection(@"Data Source=" + servername + ";Initial Catalog=master;User ID=" + user + ";Password=" + password + "");
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "exec sp_databases";
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr.GetString(0));
}






con = new SqlConnection(@"Data Source=" + serverName + ";Initial Catalog=master;User ID=" + user + ";Password=" + password + "");

Database = comboBox1.SelectedItem.ToString();//here we select database

try
{
fbd = new FolderBrowserDialog();//use for save backup of database
result = fbd.ShowDialog();
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(fbd.SelectedPath);
path = dir.ToString();//folder location
con.Open();
//query to take backup database
cmd = new SqlCommand("backup database test to disk='" + path + "\\" + databse + DateTime.Now.ToString("ddMMMyyyy") + ".Bak'", con);
cmd.ExecuteNonQuery();
//Close connection
con.Close();
MessageBox.Show("Backup of database is Done successfully");


I think this will help you……
 
Share this answer
 
Try this:
C#
private void DatabaseBackup()
        {
            string strDate = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0');
            string[] strTime = DateTime.Now.TimeOfDay.ToString().Split(':');
            string strDateTime = strDate + " " + strTime[0].PadLeft(2, '0') + strTime[1].PadLeft(2, '0');
            try
            {
                string backupPath = txtBackupLocation.Text.Trim() + "\\" + strDateTime + ".bak";
                int retVal = 0;
                DatabaseBackup(backupPath);
                if (retVal != 0)
                {
                    btnBackupDatabase.Enabled = false;
                    lblBackupStatus.Text = "Database backup successful.";
                    MessageBox.Show("Backup of database completed successfully." + Environment.NewLine + backupPath, Program.MESSAGEBOXTITLE, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    btnClose.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error [Database Backup]: " + Environment.NewLine + ex.Message, Program.MESSAGEBOXTITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                lblBackupStatus.Text = "Database backup failed.";
            }
        }


C#
public int DatabaseBackup(string backupPath)
        {
            int retVal = 0;

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
            SqlCommand cmd = new SqlCommand();
            
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = @"Backup Database To Disk = '" + backupPath + "' WITH INIT";
            try
            {
                conn.Open();
                cmd.Connection = conn;
                retVal = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
            finally
            {
                conn.Close();
            }

            return retVal;
        }
 
Share this answer
 
Comments
Ammar Programmer 30-Nov-17 9:35am    
try this where
btnBackupDatabase ? this button ?
plese put what need in form and where write code to test it
 
Share this answer
 

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