I am trying to restore a database backup file (.bak) to a newly created database using C#. I get the following inner exception:
Cannot open backup device '\GC.bak'. Operating system error 5 (Access is denied.).
RESTORE DATABASE is terminating abnormally
My server is a localDB.
void RestoreDB(string name)
{
var connection = new ServerConnection(Properties.Settings.Default.Well);
var sqlServer = new Server(connection);
var rstDatabase = new Restore();
rstDatabase.Database = name;
rstDatabase.Action = RestoreActionType.Database;
rstDatabase.Devices.AddDevice(AppDomain.CurrentDomain.BaseDirectory + "GC.bak", DeviceType.File);
rstDatabase.ReplaceDatabase = true;
rstDatabase.SqlRestore(sqlServer);
}
By default SQL Server only has access to a few specific places on the server drive (i.e. the default database and backup folder locations). It looks like you are probably trying to restore the file from a non-standard location, so you either need to grant permissions to the service account that SQL server is running under to that directory, or even easier, copy the backup file into the regular backup file location and try again.
Related
I have a database on the server shared on the local network. I would like to write an application that backs up the database from this server, but not on the server, but on the computer from which I started this application. That is, for a better understanding:
The database is on some Windows Server server. I have a laptop that is connected to the same network and has access to a database. On this laptop, I start the app, connect to the database and the .bak file is saved to the laptop, not the server.
At the moment I wrote only so much and unfortunately it doesn't work for me:
private static void CreateDatabaseBackup(string connectionString, string databaseName, string backupFilePath)
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand backupCommand = connection.CreateCommand();
backupCommand.CommandText = $"BACKUP DATABASE {databaseName} TO DISK = '{backupFilePath}'";
connection.Open();
backupCommand.ExecuteNonQuery();
connection.Close();
}
This throws me an exception:
System.Data.SqlClient.SqlException: „Cannot open backup device 'C:\Backup\backup.bak'. Operating system error 3(The system cannot find the path specified.).
BACKUP DATABASE is terminating abnormally.”
Probably because of the fact that it is trying to save the file to the server's disk, and it does not have the path specified in the variable backupFilePath
I would like .bak to be saved to the disk of the device firing the application.
How to approach this problem?
I want to backup my remote SQL Server database onto the local computer.
So far I've tried:
using (SqlConnection defaultSqlConnection = new SqlConnection(Constants.Database_Constants.GetConnectionStringFromProfile(Constants.Profiles.Staging)))
{
string pathDatabase = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\backup_production_database"+DateTime.UtcNow.ToString("d_MMM_yyyy_HH_mm_ss", CultureInfo.InvariantCulture)+".bak";
WriteLine("The backup will be stored in " + pathDatabase);
string backupDb = "BACKUP DATABASE DB_Staging TO DISK = '" + pathDatabase+ "' WITH INIT, COMPRESSION";
File.Create(pathDatabase);
using (SqlCommand backupCommand = new SqlCommand(backupDb, defaultSqlConnection))
{
defaultSqlConnection.Open();
backupCommand.ExecuteNonQuery();
}
}
But I get this error :
Cannot open backup device 'XXXX\bin\Debug\backup_production_database22_Mar_2017_08_04_42.bak'.
Operating system error 3(The system cannot find the path specified.).
BACKUP DATABASE is terminating abnormally.
I know that I could generate a script using SQL Server Management Studio but it doesn't help me. I want to backup my database in a powershell script automatically without having to go manually into SQL Server Management Studio
You cannot create a directly backup from a remote server to a local disk.
Please look this link.
We get .ydb files of firebird database from client. Currenlty we created a DSN with some additional installation/drivers and then access the tables and data inside the files.
We are planning to move this process to azure cloud service (not azure VM) so to avoid creating DSN etc. we need to access the .ydb files from c# code.
I could not open directly using firebird ado.net provider, throwing exceptions.
The below are the steps used to create DSN in the machine. It is working for long time.
Firebird ODBC setup in Windows Server
DSNName-DSNName1,
Driver-IscDbc,
Database-E:\Somefolder\FileName.ydb
Client-C:\ProgramFiles\Firebird\Firebird2_5\WOW64\fbclient.dll
Database Account- SYSDBA
Password - masterkey
Role - SYSDBA
CharSet - None
Then used the below C# code to access the FileName.ydb using the DSN.
using (var connection = new OdbcConnection("DSN=DSNName1"))
{
connection.Open();
var schema = connection.GetSchema("Tables");
var tableNames = new List<string>();
}
Now to modify the above DSN creation process, I added FirebirdSql.Data.FirebirdClient nuget package in the c# solution.
string connectionString = "User=SYSDBA;" + "Password=masterkey;" +
"Database=E:\\Somefolder\\Filename.ydb;" + "Dialect=3;" + "Charset=NONE;" +
"Role=SYSDBA;";
FbConnection fbConn = new FbConnection(connectionString);
fbConn.Open();
var schema = fbConn.GetSchema("Tables");
It throws exception on fbConn.Open(); - Unable to complete network request to host "localhost".
How to open the .ydb files in C# directly without creating a DSN?
The biggest problem you seem to have is that you do not have Firebird server installed or running, so you can't actually connect to it and ask it to open the database file.
You can download Firebird from http://www.firebirdsql.org/en/downloads/ (you will probably need Firebird 2.5) and install it. Then in a project that references FirebirdSql.Data.FirebirdClient you should be able to connect with as little as:
using (var connection = new FbConnection(#"User=username;Password=password;Database=D:\data\DB\database.fdb"))
{
connection.Open();
}
If for some reason you don't want to install Firebird server, you will need to use Firebird embedded (which can also be downloaded from the link above).
You will need to make sure that your application is either running 32 bit or 64 bit, and download the right Firebird embedded package. Put it in the path, or in the folder of your executable. In the URL you need to add ServerType=1 to get Embedded support (the default is ServerType=0):
using (var connection = new FbConnection(#"ServerType=1;User=username;Password=password;Database=D:\data\DB\database.fdb"))
{
connection.Open();
}
It is a follow-up question to my previous question in the same forum.
I would like to take a backup of my SQL Server database. Here is the code, for the backup in C#.
userConn = new SqlConnection(userdatabase);
userConn.Open();
string UserString;
UserString = "BACKUP DATABASE #DBName TO DISK = #FilePath";
String destPath = DestDirectory + "\\UserDataTable.bak";
SqlCommand cmd = new SqlCommand(UserString, userConn);
cmd.Parameters.AddWithValue("#dbName", userConn.Database);
cmd.Parameters.AddWithValue("#FilePath", destPath);
cmd.ExecuteNonQuery();
cmd.Dispose();
However, it throws an SQLException,
"Cannot open backup device
'D:\BookKeeping\Database\11_01_2013_21_15\Database\UserDataTable.bak'.
Operating system error 3(failed to retrieve text for this error.
Reason: 15105). BACKUP DATABASE is terminating abnormally."
Any Idea, what could be wrong ?
Thanks a lot for your time and your help.
"Operating system error 3" means that the directory was not found. SQL will not create the backup directory for you; you have to manually create it before running the backup command.
Make sure your SqlServer and the location where you want to create a backup is the same system. If you are using sqlServer remotely(Not located in your system) then you can not create a backup in your machine or you can not restore the database taking a .bak from your machine also.
I've written a Windows application which uses the Sql Express database server.
How can I programatically backup and restore the database through my application?
You could have your application launch a .sql file that does the backing up or restoring for you. Granted, I've mostly seen this done in a Scheduled Task, but I suppose you could do it from a triggered event inside your app.
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "C:\\path\\to\\backup.sql";
p.Start();
UPDATE:
As pointed out in the comments, this won't work if you don't have SQL Management Studio installed on the server. Alternatively, you could call a stored procedure. Upon reflecting, I'm not sure why I didn't suggest the stored proc first - probably because the other methodology was fresh on my brain due to being forced to implement it that way in a previous project.
You can request a backup from within your app by executing:
#"BACKUP DATABASE [MyDBName] TO DISK = 'c:\somedir\MyDBName.bak' WITH INIT" (ref)
Or use SQL SMO Objects SqlBackup() directly.
You could use SQL Server Management Objects
First add a reference in your project to: Microsoft.SqlServer.Smo.dll, Microsoft.SqlServer.SmoExtended.dll, Microsoft.SqlServer.SqlEnum.dll and Microsoft.SqlServer.SmoEnum.dll.
After that to Backup your Database follow this sample:
//Connect to the server
Server srv = new Server();
//If Sql Server is not local or is a named instance you could do
//Server srv = new Server("SERVERNAME");
Database db = srv.Databases("YourDB");
//Create a backup definition
Backup backup = new Backup();
backup.Action = BackupActionType.Database;
backup.BackupSetDescription = "Full backup of Adventureworks2008R2";
backup.BackupSetName = "My app Backup";
backup.Database = "YourDB";
//Configure the backup device
BackupDeviceItem backupDevice = new BackupDeviceItem("YourDB.bak", DeviceType.File);
backup.Devices.Add(backupDevice);
//Specify wether do a full backup or not
backup.Incremental = false;
//Specify log truncation mode
backup.LogTruncation = BackupTruncateLogType.Truncate;
//Do the backùp
backup.SqlBackup(srv);