Saturday, August 13, 2016

Restore Database using C#.net


                        SqlConnection Con;
                        connect = new SqlConnection(String.Format("Data Source={0};Initial Catalog={1};User Id={2};Password={3};", ServerName, "master", UserName,Password));
                        Con.Open();
                       
                       SqlCommand command;
                        command = new SqlCommand("use master", Con);
                        command.ExecuteNonQuery();
                        SqlDataAdapter da = new SqlDataAdapter(@"use master Restore FILELISTONLY FROM DISK ='" + SelectPath + "'", Con);
                        DataSet mds = new DataSet();
                        da.Fill(mds);
                        if (mds == null)
                        {
                            MessageBox.Show("File not Support");
                            return;
                        }
                        command = new SqlCommand(@"RESTORE DATABASE " + mds.Tables[0].Rows[0][0].ToString() + " FROM DISK ='" + SelectPath + "' WITH MOVE '" + mds.Tables[0].Rows[0][0].ToString() + "' TO '" + RestoreFilePath + "\\" + mds.Tables[0].Rows[0][0].ToString() + ".mdf',REPLACE, MOVE '" + mds.Tables[0].Rows[1][0].ToString() + "' TO '" + RestoreFilePath + "\\" + mds.Tables[0].Rows[0][0].ToString() + "_log.ldf',REPLACE", Con);
                        command.CommandTimeout = 0;
                        command.ExecuteNonQuery();
                      

                        Con.Close();

No comments: