Foee
Foee

Reputation: 77

How to do backup in C# application?

I will try to do a backup database from C# application. I found more tutorials how do that. In the new project copy some solution and run. All the time I got one connection error like:

"backup failed for server ".

In this line:

source.SqlBackup(server);

Do you know how I resolve this? I think that problem concerns connection to server (it's broken?).

Below you can see a Backup method:

public static void BackupDatabase(string backUpFile)
{
    ServerConnection con = new ServerConnection(@".\SQLEXPRESS");
    Server server = new Server(con);
    Backup source = new Backup();
    source.Action = BackupActionType.Database;
    source.Database = "DB";
    BackupDeviceItem destination = new BackupDeviceItem(backUpFile, DeviceType.File);
    source.Devices.Add(destination);
    source.SqlBackup(server);
    con.Disconnect();
    MessageBox.Show("Kopia wykonana!");
}

Upvotes: 2

Views: 1432

Answers (2)

James Poulose
James Poulose

Reputation: 3833

Couple of things for you to try.

  1. Make sure your database name is correct

    source.Database = "DB"; // Check the database name is actually 'DB'.

  2. I had some issues in the past using ServerConnection with a connection string, even though the syntax allows you to do so. What i did was to create an SqlConnection from the connection string and then give that to ServerConnection.

    string connectionString = "Your connection string goes here";
    
    SqlConnection sqlCon = new SqlConnection(connectionString);
    
    ServerConnection connection = new ServerConnection(sqlCon);
    
  3. I would also try initializing the backup object.

    source.Initialize = true; 
    

Upvotes: 2

Foee
Foee

Reputation: 77

Added full control for PC Users to the backup folder on C:\ drive helped! Thanks all for help! But just I have one question: how I can modify above C# code that program should be yourself create backup folder on C:\ and do a copy database? Currently I must do it manually.

Upvotes: 1

Related Questions