I have SQL Server Express running on my machine, and I would like to create a backup of a database and restore this backup on my local machine so that I can use the .mdf
and .ldf
files locally.
I have a small C# program that manages this database and allows me to execute the backup creation and restore requests. However, when I want to copy/paste the .mdf
and .ldf
files locally, I don't have access rights. Only the administrator account and the SQL Service have access.
Is there a way to perform the restore locally without sharing a folder with the server?
Backup method:
string cmd = "BACKUP DATABASE [" + "Database" + "] TO DISK='" + "\\\\srv-vm\\PJDB\\Backup\\Database.bak" + "'";
using (SqlCommand command = new SqlCommand(cmd, con))
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
command.ExecuteNonQuery();
}
Restore method:
SqlConnection objconnection = new SqlConnection(connectionstring);
ServerConnection con = new
ServerConnection(objconnection.DataSource.ToString());
Server server = new Server(con);
Restore _dataBase = new Restore();
_dataBase.Database = "db";
_dataBase.Action = RestoreActionType.Database;
_dataBase.Devices.AddDevice("\\\\srv-vm\\PJDB\\Backup\\Database.bak", DeviceType.File);
// define "file relocation" - for all "logical" files in a SQL Server database,
// define a new physical location where the file will end up at
RelocateFile relocateDataFile = new RelocateFile("Database", "\\\\srv-vm\\PJDB\\Backup" + "\\Database.mdf");
RelocateFile relocateLogFile = new RelocateFile("Database_log", "\\\\srv-vm\\PJDB\\Backup" + "\\Database_log.ldf");
_dataBase.RelocateFiles.Add(relocateDataFile);
_dataBase.RelocateFiles.Add(relocateLogFile);
_dataBase.ReplaceDatabase = true;
_dataBase.SqlRestore(server);
_dataBase.NoRecovery = false;