Restore sql database from backup file in .net technology
public static void RestoreDatabase(string DatabaseName, string BackupFilePath, string DataFilePath, string LogFilePath)
{
string[] LogicalFileName=new string[2];
string DbConnectionString = GetDatabaseConnectionString("master");
SqlConnection sqlConnection = new SqlConnection(DbConnectionString);
//LogicalName ,Type D,L
//Get Logical file name
string SQL_RestoreFILELISTONLY=" Restore FILELISTONLY FROM DISK=N'" + BackupFilePath + "'";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(SQL_RestoreFILELISTONLY,sqlConnection);
DataTable dt = new DataTable();
sqlDataAdapter.Fill(dt);
DataRow[] arrDataRow;
//Get Logical file name for Data File
arrDataRow = dt.Select("Type='D'");
LogicalFileName[0] = arrDataRow[0]["LogicalName"].ToString();
//Get Logical file name for Log File
arrDataRow = dt.Select("Type='L'");
LogicalFileName[1] = arrDataRow[0]["LogicalName"].ToString();
StringBuilder sbRestoreDatabase = new StringBuilder();
sbRestoreDatabase.Append(" RESTORE DATABASE ").AppendLine(DatabaseName);
sbRestoreDatabase.Append(" FROM DISK=N'").Append(BackupFilePath).AppendLine("' ");
sbRestoreDatabase.AppendLine(" with ");
sbRestoreDatabase.AppendLine(" Replace, ");
sbRestoreDatabase.Append(" MOVE '").Append(LogicalFileName[0]).Append("' TO '").Append(DataFilePath).AppendLine("', ");
sbRestoreDatabase.Append(" MOVE '").Append(LogicalFileName[1]).Append("' TO '").Append(LogFilePath).AppendLine("', STATS=5 ");
SqlCommand sqlCommand = new SqlCommand(sbRestoreDatabase.ToString());
sqlCommand.CommandTimeout = 1800;
sqlCommand.Connection = sqlConnection;
sqlCommand.Connection.Open();
try
{
sqlCommand.ExecuteNonQuery();
}
finally
{
sqlCommand.Connection.Close();
sqlDataAdapter.Dispose();
sqlCommand.Connection.Dispose();
sqlCommand.Dispose();
}
}