kubal5003
kubal5003

Reputation: 7254

SQL Server perform backup with C#

I've investigated the possibilities of creating database backups through SMO with C#. The task is quite easy and code straightforward. I've got only one question: how can I check if the backup was really created?

SqlBackup.SqlBackup method returns no parameters and I don't even know if it throws any exceptions. (the only thing that I know is that it is blocking, because there's also SqlBackupAsync method)

I would appreciate any help.

Upvotes: 6

Views: 905

Answers (2)

kubal5003
kubal5003

Reputation: 7254

I've investigated the problem using Reflector.NET (I suppose this is legal since RedGate is Ms Gold Certified Partner and Reflector.NET opens .NET libraries out of the box). As I found out the method throws two types of exceptions:

FailedOperationException - in most cases, other exceptions are "translated" (I suppose translating means creating new FailedOperationException and setting InnerException to what was actually thrown)

UnsupportedVersionException - in one case when log truncation is set to TruncateOnly and server major version is more or equal to 10 (which is sql server 2008?)

This solves my problem partially, because I'm not 100% sure that if something goes wrong those exceptions will actually be thrown.

Upvotes: 0

Arrabi
Arrabi

Reputation: 3778

you can and its very possible to do what you asked for,

but doing the backup it self using SMO its not very hard, but the hard part is managing the backup and the restore.

it would be hard to put all the code here, but its wont fit. so I will try my best to put the lines you need.

SqlBackup.SqlBackup doesn't return any value, its a void function. but it takes one parameter which is "Server", try out the following code:

Server srvSql;

//Connect to Server using your authentication method and load the databases in srvSql
// THEN

Backup bkpDatabase = new Backup();
bkpDatabase.Action = BackupActionType.Database;
bkpDatabase.Incremental = true; // will take an incemental backup
bkpDatabase.Incremental = false; // will take a Full backup 
bkpDatabase.Database = "your DB name";
BackupDeviceItem bDevice = new BackupDeviceItem("Backup.bak", DeviceType.File);
bkpDatabase.Devices.Add(bDevice );

bkpDatabase.PercentCompleteNotification = 1;// this for progress
bkpDatabase.SqlBackup(srvSql);
bkpDatabase.Devices.Clear();

Upvotes: 1

Related Questions