tags:

views:

636

answers:

5

How easy is it to backup a Database via C# code? I see lots of related questions, but no real answers.

+3  A: 

SQL Management Objects - Microsoft.SqlServer.Management.Smo

It has the methods you need to complete that action.

bioskope
+3  A: 

Or: Generate your backup script in Management Studio, put it in a stored procedure, run procedure from C# code.

CREATE PROCEDURE sp_backup
AS
BEGIN
    BACKUP DATABASE [YourDatabase] TO  DISK = N'C:\YourPathAndFile.bak' 
    WITH NOFORMAT, NOINIT,  
    NAME = N'Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
END
GO
cdonner
+2  A: 

Should be quite easy providing you have the right permissions.

2 ways that come to mind, there's the already mentioned SQL Management objects, I found a nice project that makes use of these here

You can always just throw a T-SQL backup command at the server through the ADO.Net objects too. Msdn reference to the main command you'll need here

keith
Ensuring the Permissions isn't an issue
Harry
+3  A: 

See using SMO Library from c#

on how to use SMO library from c# to perform adminstrator tasks such backup and restor.

Abdullah BaMusa
+2  A: 

If you want to work with the stream of bytes in C#, for instance compressing the stream before writing to disk, you're welcome to look at the code from my project, SQL Server Compressed Backup. It has a small VDI (the SQL Server virtual device API) DLL wrapper written in C++ faithfully exposing each VDI option to .Net, and the rest (the bulk) of the code is written in C#.

Clay Lenhart