SQL Server Database BackUp Using C# _ Dot Net World

6
12/28/13 SQL Server Database BackUp using C# | Dot Net World manish4dotnet.blogspot.in/2013/03/DatabaseBackupusingCSharp.html 1/6 C# | ASP.Net | VB.Net | SQL Server | jQuery | Java Script | LINQ | XML | Web Application Dot Net World Home About Me Index Contact Me ASP.Net SQL Server C# Gridview jQuery Java Script XML LINQ Blogging You are here » Home » SQL Server » SQL Server Database BackUp using C# FRIDAY, MARCH 8, 2013 SQL Server Database BackUp using C# There are various ways to take the SQL Server database backup. You can take the database backup using SQL Server backup wizard or using SQL Server BackUp Database statement. Here I am going to describe how to take the SQL Server database backup programatically using C# and SQL Server Management Objects (SMO). In my previous posts, I explained Partial Methods,Contextual Keyword, C# Static Methods and some other articles related to C#, ASP.Net and SQL Server . SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server . For taking the database backup using C#, you have to add the following references in your application- Microsoft. SqlServer .ConnectionInfo Microsoft.SqlServer.Management.Sdk.Sfc Microsoft.SqlServer.Smo Microsoft.SqlServer.SmoExtended Microsoft.SqlServer.SqlEnum In your .CS file you will have to use the following namespaces- using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlServer.Management.Common; After using above namespaces, write the following code to take the database backup- public void BackupDatabase( string databaseName, string userName, string password, string serverName, string destinationPath) { //Define a Backup object variable. Backup sqlBackup = new Backup (); //Specify the type of backup, the description, the name, and the database to be backed up. sqlBackup.Action = BackupActionType .Database; sqlBackup.BackupSetDescription = "BackUp of:" + databaseName + "on" + DateTime .Now.ToShortDateString(); sqlBackup.BackupSetName = "FullBackUp" ; sqlBackup.Database = databaseName; //Declare a BackupDeviceItem Search SEARCH SPONSORS FOLLOW BY EMAIL Email address... Submit SUBSCRIBE ^ Scroll to Top Dot Net World 107 people like Dot Net World. Facebook social plugin Like Like

description

By this tutorial we learn how to take SQL Server Database BackUp using C#.

Transcript of SQL Server Database BackUp Using C# _ Dot Net World

Page 1: SQL Server Database BackUp Using C# _ Dot Net World

12/28/13 SQL Server Database BackUp using C# | Dot Net World

manish4dotnet.blogspot.in/2013/03/DatabaseBackupusingCSharp.html 1/6

C# | ASP.Net | VB.Net | SQL Server | jQuery | Java Script |

LINQ | XML | Web Application

Dot Net World

Home About Me Index Contact Me

ASP.Net SQL Server C# Gridview jQuery Java Script XML LINQ Blogging

You are here » Home » SQL Server » SQL Server Database BackUp using C#

FRIDAY, MARCH 8, 2013

SQL Server Database BackUp using C#

There are various ways to take the SQL Server database backup. You can take the database backup using

SQL Server backup wizard or using SQL Server BackUp Database statement. Here I am going to

describe how to take the SQL Server database backup programatically using C# and SQL Server

Management Objects (SMO).

In my previous posts, I explained Partial Methods,Contextual Keyword, C# Static Methods and some other

articles related to C#, ASP.Net and SQL Server .

SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all

aspects of managing Microsoft SQL Server.

For taking the database backup using C#, you have to add the following references in your application-

Microsoft.SqlServer.ConnectionInfo

Microsoft.SqlServer.Management.Sdk.Sfc

Microsoft.SqlServer.Smo

Microsoft.SqlServer.SmoExtended

Microsoft.SqlServer.SqlEnum

In your .CS file you will have to use the following namespaces-

using Microsoft.SqlServer.Management.Smo;

using Microsoft.SqlServer.Management.Common;

After using above namespaces, write the following code to take the database backup-

public void BackupDatabase(string databaseName, string userName, string password, string

serverName, string destinationPath)

//Define a Backup object variable.

Backup sqlBackup = new Backup();

//Specify the type of backup, the description, the name, and the database to be backed

up.

sqlBackup.Action = BackupActionType.Database;

sqlBackup.BackupSetDescription = "BackUp of:" + databaseName + "on" +

DateTime.Now.ToShortDateString();

sqlBackup.BackupSetName = "FullBackUp";

sqlBackup.Database = databaseName;

//Declare a BackupDeviceItem

Sea rch

SEARCH

SPONSORS

FOLLOW BY EMAIL

Email address... Submit

SUBSCRIBE^ Scroll to Top

Dot Net World

107 people like Dot Net World.

Facebook social plugin

LikeLike

Page 2: SQL Server Database BackUp Using C# _ Dot Net World

12/28/13 SQL Server Database BackUp using C# | Dot Net World

manish4dotnet.blogspot.in/2013/03/DatabaseBackupusingCSharp.html 2/6

Posted by Manish Dubey at 5:50 PM

26 Comments

Labels: ASP.Net, C#, SQL Server

BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath + "FullBackUp.bak",

DeviceType.File);

//Define Server connection

ServerConnection connection = new ServerConnection(serverName, userName, password);

//To Avoid TimeOut Exception

Server sqlServer = new Server(connection);

sqlServer.ConnectionContext.StatementTimeout = 60 * 60;

Database db = sqlServer.Databases[databaseName];

sqlBackup.Initialize = true;

sqlBackup.Checksum = true;

sqlBackup.ContinueAfterError = true;

//Add the device to the Backup object.

sqlBackup.Devices.Add(deviceItem);

//Set the Incremental property to False to specify that this is a full database backup.

sqlBackup.Incremental = false;

sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);

//Specify that the log must be truncated after the backup is complete.

sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

sqlBackup.FormatMedia = false;

//Run SqlBackup to perform the full database backup on the instance of SQL Server.

sqlBackup.SqlBackup(sqlServer);

//Remove the backup device from the Backup object.

sqlBackup.Devices.Remove(deviceItem);

Happy coding!!

+1 Recommend this on Google

26 comments

WHAT 'S T HIS?AROUND THE WEB

ALSO ON DOT NET WORLD

How To- Bind Data to Gridview using jQuery in

ASP.Net ~ Dot Net World : … 8 comments

How To- Get hard dr ive information using C# ~

Dot Net World : Your Source … 2 comments

How To- Send DataGridView Data in Email in

Window Form Application ~ Dot … 6 comments

How To- Send Gridview Data in Email in ASP.Net

using C#, VB.Net ~ … 14 comments

14 Social Security Benefits You

Haven't Been Taking

Moneynews

9 Ways to Have a Women's

Night In

Citi Women & Co.

5 Ways to Stay Young and Fit

Stack

Join the discussion…

Best Community Login Share

Kaushal Mehra • 7 months ago

Used exactly the same code on click of button on my webpage. Getting below error.

"Backup failed for server servername"

exception thrown at line: sqlBackup.sqlBackup(sqlServer)

Calling method like this:

protected void Button1_Click(object sender, EventArgs e)

1

Posts

Comments

How To- Search recordsor data in gridview using jQuery(16 Jul 2013)(0 comment)

How To- SendDataGridView Data in Email inWindow Form Application(23 Jul 2013)(0 comment)

SQL Server- UserDefined Function to Parse HTML-Strip HTML -Without UsingRegular Expression(06 Aug 2013)(0 comment)LINQ- Differencebetween Single andSingleOrDefault- Single vsSingleOrDefault(12 Aug 2013)(0 comment)

RECENT POSTS

2013 (82)

Dec 2013 (1)

Oct 2013 (1)

Aug 2013 (5)

Jul 2013 (2)

Jun 2013 (4)

May 2013 (8)

Apr 2013 (17)

Mar 2013 (18)

jQuery- Page Scroll to Top withjQuery | How to ad...

Automatically Refresh Page UsingJava Script

How to Create a Textarea CharacterCounter / Limit...

SQL Server STR Function

Export Gridview to PDF in ASP.Net

SPACE Function in SQL Server

Restore SQL Server Database UsingC#

SQL Server Database BackUp usingC#

SQL Server LOWER Function

C# Anonymous Method

SQL Server SUBSTRING Function

Animated Sliding Recent Post WidgetFor Blogger

Change Input to Upper Case usingJava Script

SQL Server UPPER Function

Exporting Query Results to CSVusing SQLCMD

SQL Server STUFF Function

SQL Server LEN Function

SQL Server UNICODE Function

Feb 2013 (16)

Jan 2013 (10)

BLOG ARCHIVE

Page 3: SQL Server Database BackUp Using C# _ Dot Net World

12/28/13 SQL Server Database BackUp using C# | Dot Net World

manish4dotnet.blogspot.in/2013/03/DatabaseBackupusingCSharp.html 3/6

• Reply •

BackupDatabase("databasenamexxx","usernamexxx","passwordxxx","servernamexxx","C:\\Users\\kaushal\\Downloads");

Please help.

2

• Reply •

Manish Dubey • 7 months agoM o d Kaushal Mehra

Can you give me more detail about Error.

Please use try-catch block to get more specific error.

That will be more helpful for me to help you!!

2

• Reply •

Nandhinee • a month ago Kaushal Mehra

I too get the same error. Backup failed for Server server name? Can u pls help.

• Reply •

Deenu • 4 months ago

how to take database backup using windows authentication mode???

• Reply •

Vikram • 5 months ago

Sir jee,,Could You tell me How to add those 4 namespaces?

I am Wondering Every where,,but could not find it yet.

Plz Do help

• Reply •

Manish Dubey • 5 months agoM o d Vikram

For using those namespaces which are show above. You have to add the references of these

namespaces. For this-

Go to Your Application and Right Click on References folder and select Add Reference.

Now Go to "Browse" Tab and browse the following path-

"C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies"

Now Select the following dlls

Microsoft.SqlServer.ConnectionInfo.dll

Microsoft.SqlServer.Management.Sdk.Sfc.dll

Microsoft.SqlServer.Smo.dll

Microsoft.SqlServer.SmoExtended.dll

Microsoft.SqlServer.SqlEnum.dll

• Reply •

Vikram • 5 months ago Manish Dubey

Bhai Done It,,

Thank Uuuuuuuuuu

A Tight Hug :)

• Reply •

Vikram • 5 months ago Vikram

Sir It's Working well,,there is another problem

as I am giving the database name and path statically,it does not allow me to

over write in that same name and same location,In result back up getting

failed after first bak up.

so i created a text field where user have to give the data base name.

but my query is how this is possible to overwrite that same file name and in

same location,

Do Suggest,Thank u

Manish Dubey • 5 months agoM o d Vikram

You can not save the same file with same name in one place.

If you want to over write the previous file, you should check that file is exists or

not on you location if exists then first ti delete that file then save new file.

For all these use following links-

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

2012 (32)

Manish Dubey

Follow 123

View my complete profile

ABOUT ME

BLOG ROLL

Site Home

SQL Authority

2,000 Things about C#

ASP.Net C# SQL Server Java

Script Code Snippest Jquery Tipsand Tricks GridView Linq

CATEGORIES

CSS Database

Blogging Tips DataTable Mail VB.Net Web

Serv ice XML ASp.Net Controls Freshers

Google API LINQ to SQL PDF Reflection

Window Application iTextSharp A ja x

A ssem blies Blog g er C Colla t ion Con str u ctor

Ex ception FileUploa d GMa il Gen er ic Gen er ic

Collect ion IL LIst Lin q to Da ta Ta ble Pr im a r y

Key Qu er y Str in g Ra d Con tr ol SMTP Str in g

Ma n ipu la t ion Tiff User Con tr ols V a lida t ion

You Tu be ZIp File

Ask Manishnow

Page 4: SQL Server Database BackUp Using C# _ Dot Net World

12/28/13 SQL Server Database BackUp using C# | Dot Net World

manish4dotnet.blogspot.in/2013/03/DatabaseBackupusingCSharp.html 4/6

• Reply •

http://www.dotnetperls.com/fil...

http://www.dotnetperls.com/fil...

• Reply •

Vikram • 5 months ago Manish Dubey

Thank You Sir jee :)

• Reply •

Chris t ian • 6 months ago

everything went good! thank you! i just got an error "Backup failed" then i add the

"SQLServer2005MSSQLUser$MYSERVERNAME$MSSQLSERVER" permit on group or users

(Security tab) on the destination folder and worked as expected

• Reply •

Raj • 4 months ago Christian

shud i use same for sql server 2008..???

• Reply •

Manish Dubey • 4 months agoM o d Raj

Yes use can use it for Server 2008 also

• Reply •

Manish Dubey • 6 months agoM o d Christian

Thanks Christian!!

• Reply •

Sameer Das • 7 months ago

can it work in online

• Reply •

Manish Dubey • 7 months agoM o d Sameer Das

Yes, It will.

Have you try it online?

• Reply •

Server management • 8 months ago

Thanks for your posting this blog. Actually i was searchig for server technical solutions on net. Found

your blog. After my successful research i found an website IT Monteur who is expert in this field. I

hope you also like their service.

If you're looking for highly qualified professional server management. If you'd like the services to be

affordable but will never sacrifice top quality for the sake of with IT monteur today. If all or most of

your business depends on reliable operation of your servers.

If you’re looking for highly qualified professional server management

If you’d like the services to be affordable but will never sacrifice top quality for the sake of cheap

price.

.Our experts will help you select the service package which satisfies your company’s needs the best.

Whether you need to secure your Linux server or setting it from scratch, manage your network

infrastructure or fine tune a database server – from small one-time job to a fully outsourced solution

– IT MONTEUR will meet your needs. Our clients are always satisfied with the final results, and so

will you. Contact at +91 120 6498887 or visit at www.itmonteur.net.

Industry most useful services:-

1) Server management

2) Network monitoring

3) Security services

4) Anti Virus & Anti Spam Solutions

IT monteur - a Complete IT Solution provider in Delhi, Noida, Gurgaon.

• Reply •

Manish Dubey • 8 months agoM o d Server management

Thanks for you valuable information!!

deepak • 9 months ago

I didn't know this Manish.Wouldn't it be simpler to just run the following syntax from c# instead of

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Page 5: SQL Server Database BackUp Using C# _ Dot Net World

12/28/13 SQL Server Database BackUp using C# | Dot Net World

manish4dotnet.blogspot.in/2013/03/DatabaseBackupusingCSharp.html 5/6

<< Restore SQL Server Database Using C# SQL Server LOWER Function >>Home

Subscribe to: Post Comments (Atom)

• Reply •

I didn't know this Manish.Wouldn't it be simpler to just run the following syntax from c# instead of

SMO

BACKUP DATABASE AdventureWorks

TO DISK = 'C:\AdventureWorks.BAK'

GO

• Reply •

Manish Dubey • 9 months agoM o d deepak

Your are right . There are several ways of taking backup of Database using C#, SQL Server

scripts etc. Through this article I am not only target to tell about taking Database backup,here

I also want to tell my readers about SMO and how you can use its features.

• Reply •

Ashutosh • 9 months ago

how its use in Sql Server version 10.50

give rsponse in my Id:- [email protected]

• Reply •

Salem AL-Badawi • 10 months ago

thank you it's great

• Reply •

Manish Dubey • 10 months agoM o d Salem AL-Badawi

Thanks Salem

• Reply •

Manish Dubey • 10 months ago

Thanks

• Reply •

Video Product ion • 10 months ago

Very interesting blog. Thanks for sharing with us.

• Reply •

Sudhir DBAKings • 6 months ago Video Production

Nice post very helpful

dbakings

Subs cribe Add Dis qus to your s i te

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

Share ›

IF YOU ENJOYED THIS POST PLEASE TAKE 5 SECONDS TO SHARE IT.

22

Page 6: SQL Server Database BackUp Using C# _ Dot Net World

12/28/13 SQL Server Database BackUp using C# | Dot Net World

manish4dotnet.blogspot.in/2013/03/DatabaseBackupusingCSharp.html 6/6

hgpromo

Join this sitew ith Google Friend Connect

Members (6)

Already a member? Sign in

FOLLOWERS

search engine info

BlogCatalog

Blog Directory Top Blog Sites

Blogs Candles Promote Blog

Blog Directory Blog Community

Jar Candles Blog Submission

HyperSmash

http://www.casino-online.us/

LISTED IN

Blogger- Adding Facebook LikeBox into Blogger Blog

Promoting your blog or website, Facebook page is a greatway. Facebook like box is a

widely used social plugin from Facebookdevelopers. F...

SQL Server Database BackUp using C#

There are various ways to take the SQLServer database backup. You can take thedatabase backup using SQL Server backupwizard or using ...

How To- Bind Data to Gridviewusing jQuery in ASP.Net

In this post, I am explaininghow to bind data to Gridviewusing jQuery in ASP.Net

through Ajax call. In previous posts, Iexplained P...

Creating Captcha Code in ASP.Net

Before entering in to the topic first we mustknow “What is the Captcha code?” and “Whywe used it?” Most of the web sites having theCap...

Upload and Read the Excel fileusing C#

This example will show youhow to Upload the excel fileand then read the excel file

data using C# and display it on Gridview.Drag and...

Export Gridview to PDF inASP.Net

In web development, Gridviewis the most frequently usedcontrol for data display in

ASP.Net . Sometimes we have a requirementto export ...

How To- Search records ordata in gridview using jQuery

In my previous post, Iexplained bind the gridviewusing jQuery . Here I am going

to show you how to search record or datawith in Gridvie...

MUST READ!!!

SQL Server Database BackUp using C#

There are various ways to take the SQLServer database backup. You can take thedatabase backup using SQL Server backupwizard or using ...

C#: Difference between“throw” and “throw ex” in C#.Net Exception

In day to day development, weall are very familiar with

Exception handling. We pretty much allknow that we should wrap the code whichma...

How To- Convert Data Tableinto List

Recently I have posted anarticle Convert a Generic Listto a Datatable . Today I am

explaining here the reverse way of myprevious artic...

How To- Search records ordata in gridview using jQuery

In my previous post, Iexplained bind the gridviewusing jQuery . Here I am going

to show you how to search record or datawith in Gridvie...

ASP.Net- Create HindiTextBox Using GoogleTransliteration in ASP.Net

Here, I am explaining you howto create a hindi textbox in

ASP.Net using Google Transliteration .HereI am mainly targeting english to...

WEEKLY POPULAR POSTS

Manish Dubey

123 have me in circles View all

Add to circles

GOOGLE+ FOLLOWERS

Copyright (c) 2013-14 Dot Net World. Powered by Blogger.