I am trying to back up a SQL Server database to my web server. I am using System.Data.SqlClient.SqlConnection
to execute the T-SQL command. To set the backup path, I am retrieving my web server root path with IHostingEnvironment.ContentRootPath
.
However, when I execute the command, the following exception is thrown:
System.Data.SqlClient.SqlException (0x80131904): Cannot open backup device 'E:[...]\www'.
Operating system error 3(The system cannot find the path specified.)
How come the SqlClient
doesn't recognize my web server path? The drive letter of my DB server is the same as my web server. I am using a shared hosting, if it can help.
Here is my full code:
// _iConfiguration and _hostingEnvironment are set through dependency injection
var connectionStringBuilder = new SqlConnectionStringBuilder {
ConnectionString = _iConfiguration["ConnectionStrings:DefaultConnection"]
};
var commandText =
$@"BACKUP DATABASE [{connectionStringBuilder.InitialCatalog}] TO DISK = N'{_hostingEnvironment.ContentRootPath}' WITH NOFORMAT, INIT,"
+ "NAME = N'backup-{DateTime.Now}', SKIP, NOREWIND, NOUNLOAD, STATS = 10";
using (var connection = new SqlConnection(connectionStringBuilder.ConnectionString))
{
connection.Open();
connection.InfoMessage += Connection_InfoMessage;
using (var command = connection.CreateCommand())
{
command.CommandText = commandText;
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();
}
}
It seems the SQL Account does not have WRITE permission to write the backup file at the content root.
I would suggest better create separate path (instead of content root) for running the backup query. The backup then would be added to that folder only.
Also, please refer this thread for more details : Cannot open backup device. Operating System error 5
User contributions licensed under CC BY-SA 3.0