user599977
user599977

Reputation: 331

How to create a SqlServer database backup with .Net?

I want to make a database backup with this C# code:

connect = new SqlConnection(con);
connect.Open();

// Execute SQL
SqlCommand command = new SqlCommand
(
    @"backup database MY_database to disk='d:\SQLBackup\wcBackUp1.bak' with init, stats=10",
    connect
);

command.ExecuteNonQuery();
connect.Close();

When I run it, the following error message shows up:

Cannot open backup device 'd:\SQLBackup\wcBackUp1.bak'. Operating system error 3(The system cannot find the path specified.).

If I change the path to d:\wcBackUp1.bak it seems to be ok, is without error, but the file does not exist, it was not generated.

If I run in SQL the command I have the message that it was 100% processed, but I didn`t see the file.

Could someone help me please?

Upvotes: 1

Views: 3934

Answers (3)

AbrahamJP
AbrahamJP

Reputation: 3440

Make sure the location "d:\SQLBackup\" exist in your database server and not on your client machine.

Upvotes: 5

sgmoore
sgmoore

Reputation: 16077

Two things to check.

The Sql Service may not have access to the d:\sqlbackup folder. Old Sql installs used to default to install the service with full access to the machine, but newer instances tighten that up. You could try changing the path to the directory where the default backups are stored.

Secondly, if the sql server is not on the same machine that you are running this program, then you must remember that the D: will be the D: on the sql server and not your local machine

Upvotes: 3

tomfanning
tomfanning

Reputation: 9670

Fundamentally, the Windows account that the SQL Server service runs under must have write permissions on the specified folder.

You can check what account this is by looking in SQL Server Configuration Manager, under SQL Server Services (look at the Log On As column)

Check what permissions that account actually has on the target folder using Explorer -> right click folder -> properties -> security -> advanced -> effective permissions.

One way to check that this is the problem is to change your code to back up to your SQL instance's backup folder, where the permissions are likely to be correct. For example

C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup

Upvotes: 0

Related Questions