m using visual studio 2005 and sql server 2005.
i want to create a backup of the sql server which m doin using the following code..

if (saveBackupDialog.ShowDialog() == DialogResult.OK)
                SqlCommand cmd = new SqlCommand();
                cmd.CommandText = @"backup database dbname to disk =@loc with init,stats=10";
                cmd.Parameters.Add("@loc", SqlDbType.VarChar);
                cmd.Parameters["@loc"].Value = saveBackupDialog.FileName.ToString() + ".bak";
                cmd.Connection = Module1.sqlcon;

however m unable to restore the backup.
ive used a couple of codes

if (openFileDialog1.ShowDialog() == DialogResult.OK)

Restore rDatabase = new Restore();

// Set the restore type to a database restore
rDatabase.Action = RestoreActionType.Database;

// Assign a db to restore operation
rDatabase.Database = "coloursoft";

// Set the backup device to restore from file
BackupDeviceItem bkDevice = new BackupDeviceItem(openFileDialog1.FileName, DeviceType.File);

// Add the backup device to the restore type

// Replace the Db if already exists
rDatabase.ReplaceDatabase = true;
Server srv = new Server("server = ABC;uid=sa;pwd=sasa");

if (File.Exists(openFileDialog1.FileName))
// restore
catch (Exception ex)

i get the following error

Restore failed for Server 'server = ABC;uid=sa;pwd=sasa'.

also tried the following code

SqlConnection connect;
                    string con = "Data Source = localhost; Initial Catalog=master ;Integrated Security = True;";
                    connect = new SqlConnection(con);
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = connect;
                    cmd.CommandText = "use master";

                    cmd.CommandText = @"restore database coloursoft from disk = @loc with replace, MOVE 'coloursoft' TO 'C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\Data\coloursoft.mdf',
                    MOVE 'coloursoft_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\Data\coloursoft_Log.ldf'
                    cmd.Parameters.Add("@loc", SqlDbType.VarChar);
                    cmd.Parameters["@loc"].Value = openFileDialog1.FileName.ToString();


i get the following exception

Exclusive access could not be obtained because the database is in use.
RESTORE DATABASE is terminating abnormally.

problm solved dont no how...thnx ne ways...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.