How easy is it to backup a SQL Server database via C# code?
I see lots of related questions, but no real answers.
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
on how to use SMO library from c# to perform adminstrator tasks such backup and restor.
Here is a script to put database backup content into a stream (as a "select" result), that can be useful to create backup programmaticaly WITHOUT any shared folder. The only thing you needs is the connection to a server. Tested for MSSQL 2008 R2.
-- переменные
DECLARE @dbName nvarchar(MAX);
SET @dbName = N'AdventureWorks';
DECLARE @backupFileName nvarchar(MAX);
SET @backupFileName = N'C:\Temp\' + @dbName + N'.bak';
--EXECUTE (N'PRINT N''Создание бэкапа '+ @backupFileName + '''')
-- создание временной папки
EXEC xp_cmdshell N'mkdir C:\Temp', no_output;
-- бэкап с перетиранием имеющегося файла
DECLARE @sqlScript nvarchar(MAX);
SET @sqlScript = N'BACKUP DATABASE ['
+ @dbName
+ '] TO DISK = N'''
+ @backupFileName
+ ''' WITH NOFORMAT, INIT, NAME = N'''
+ @dbName
+ '-Full Database Backup'', SKIP, NOREWIND, NOUNLOAD, STATS = 10';
--SELECT @sqlScript AS backupScript
EXECUTE (@sqlScript);
-- похоже, файл в 3ГБ можно вычитать... но памяти на это уходит ОЧЕНЬ МНОГО
-- вычитывание файла
SET @sqlScript = N'
SELECT N''' + @backupFileName + ''' AS [backupFileName], BulkColumn AS [backupContent]
FROM OPENROWSET (BULK ''' + @backupFileName + ''', SINGLE_BLOB) MyFile';
--SELECT @sqlScript AS openRowsetScript
EXECUTE (@sqlScript);
-- удаление файла
SET @sqlScript = N'EXEC xp_cmdshell ''del "' + @backupFileName + '"'', no_output';
EXECUTE (@sqlScript);
The result is like follows:
backupFileName backupContent
C:\Temp\AdventureWorks.bak 0x54415045000003008C000E01000000000000000000000000000...
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
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#.