Restoring a database using C#

This code works perfectly and can be configured in any manner:
I was struggling due to command timeout and WITH RECOVERY options not present in my code earlier...... Please note that if your database has differential files, set the tsql to NORECOVERY:

string dataFileName = string.Empty;
string logFileName = string.Empty;
string getRestoreQueryList = @" RESTORE FILELISTONLY FROM DISK = N'C:\Test\Ishwar.bak'";
SqlCommand getRestoreQueryListCommand = new SqlCommand(getRestoreQueryList, con);
SqlDataAdapter adp = new SqlDataAdapter(getRestoreQueryList, con);
DataSet ds = new DataSet();
adp.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows)
{
if ("PRIMARY" == dr["FileGroupName"].ToString())
{
dataFileName = dr["LogicalName"].ToString();
}
else
{
logFileName = dr["LogicalName"].ToString();
}
}

string restore = @"RESTORE DATABASE [TestIshwar] FROM DISK = C:\Test\Ishwar.bak'
WITH RECOVERY, REPLACE ,MOVE N'" + dataFileName + @"' TO 'C:\Test\Ishwar.mdf',
MOVE N'" + logFileName + @"' TO 'C:\Test\Test_Ishwar.ldf' ";
SqlCommand restoreCommand = new SqlCommand(restore, con);
restoreCommand.CommandTimeout = 0;
restoreCommand.ExecuteNonQuery();


Let me know if anyone found this useful......

Comments

Popular posts from this blog

Load Data into Azure DW using C# in an SSIS script task

Branding your SharePoint site in a super fast way - Emgage

Power BI To Embed Or Not To Embed