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

I would like to Backup and Restore my application's dataBase, using SMO commands.
Problem is :
When I restore my file called " tpMedia_Database.bak " , It creates a file named " tpMedia_Database_new.mdf" based on my codes , but if I restore it again, it does not work.
I mean , to restore that file again, I have to change the destination file name , to a new one, like "tpMedia_Database_new_02" ..! How could I restore and overwrite restored files ?



Here is my Restore codes :


private void btnRestoreDBBackup_Click(object sender, EventArgs e)
{
    try
    {
        cn.Open();
        SrvCon = new ServerConnection(cn);
        srv = new Server(SrvCon);
        res = new Restore();
        string testFolder = MCS.Properties.Settings.Default.ArchievePath + @"\Resources\BackUp";
        string databaseName =Path.GetFileNameWithoutExtension(srv.Databases[cn.Database].Name);

        string fileName = string.Format("{0}\\{1}.bak", testFolder, databaseName);
        res.Devices.Add(new BackupDeviceItem(fileName, DeviceType.File));

        string destinationDatabaseName = string.Format("{0}_new", databaseName);
        Database currentDatabase = srv.Databases[cn.Database];

        string currentLogicalData = currentDatabase.FileGroups[0].Files[0].Name;
        string currentLogicalLog = currentDatabase.LogFiles[0].Name;

        RelocateFile reloData = new RelocateFile(currentLogicalData, string.Format(@"{0}\{1}.mdf", testFolder, destinationDatabaseName));
        RelocateFile reloLog = new RelocateFile(currentLogicalLog, string.Format(@"{0}\{1}_Log.ldf", testFolder, destinationDatabaseName));
        res.RelocateFiles.Add(reloData);
        res.RelocateFiles.Add(reloLog);
        res.Database = destinationDatabaseName;
        res.ReplaceDatabase = true;
        res.SqlRestore(srv);
    }

    catch (SmoException ex)
    {
        throw new SmoException(ex.Message, ex.InnerException);
    }
    catch (IOException ex)
    {
        throw new IOException(ex.Message, ex.InnerException);
    }
    cn.Close();

}


Thanks for helping,
MSD.
Posted
Updated 23-Aug-14 7:13am
v4

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