BackUP a Sql Data Base by C# Code

Backup-Sql-Data-Base-by-C#

There some ways to back Up a Data base, in this project a get a full back up from a database by using C#. However; we can customize the code to only backup data or exclude some tables to backup.
This Back up will Contain all Schema and Data together and generate a sql Code for us that
by Executing that code all the Data and Schema will be created for us.
So, an Important tip is that to restore a data base be using the generated code first Create an empty Data base then Execute the Sql Code.

To write this code first download nuget Microsoft.SqlServer.SqlManagementObjects by typing code below in Package Manager Console of Visual Studio.

Install-Package Microsoft.SqlServer.SqlManagementObjects 

then, add namespace Microsoft.SqlServer.Management.Smo (Code below)

using Microsoft.SqlServer.Management.Smo;

The C# Code that will Back UP a data base for us is below.

string outputFileName = @"d:/4.sql";
            StringBuilder sb = new StringBuilder();
            Server srv = new Server(new Microsoft.SqlServer.Management.Common.ServerConnection("[Server IP]", "[Sql User]", "[Sql Password]"));
            Database dbs = srv.Databases["EShop"];                // EShop is The Database that I want to backUP
            ScriptingOptions options = new ScriptingOptions();
            options.ScriptData = true;
            options.ScriptDrops = false;
            options.FileName = outputFileName;
            options.EnforceScriptingOptions = true;
            options.ScriptSchema = true;
            options.IncludeHeaders = true;
            options.AppendToFile = true;
            options.Indexes = true;
            options.WithDependencies = true;
            options.DriAll = true;

            foreach (Table tbl in dbs.Tables)
            {
                tbl.EnumScript(options);
            }

in the code below Input the Sql Connection of Data Base that you want to create back UP Sql Code of that.

ServerConnection("[Server IP]", "[Sql User]", "[Sql Password]")

and in the code below choose the output Sql File

        string outputFileName = @"d:/4.sql";