Create database file (.sdf) if doesn't exists? - c#

Just wondering about some practice about this;
I have made a simple visual C# program with local database (SQL CE) (dB.sdf file).
Let's say user deletes the dB.sdf file and try to open the exe program - nothing happens (the exe file starts but closes again).
What's the typically practice here? Is it that the program just won't start or is it to make the program create a database file if it doesn't exists?
If it is the latter, how is it done?

The second approach is more wise as your program is uselsess if it depends on database which gets deleted.
string connStr = "Data Source = DBName.sdf; Password = DBPassword";
if (!File.Exists("DBName.sdf")){
try {
SqlCeEngine engine = new SqlCeEngine(connStr);
engine.CreateDatabase();
SqlCeConnection conn = new SqlCeConnection(connStr);
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "CREATE TABLE TableName(Col1 int, Col2 varchar(20))";
cmd.ExecuteNonQuery();
}
catch (SQLException ex){
// Log the exception
}
finally {
conn.Close();
}
}

string fileName = txtEditFolderPath.Text + "\\" + txtEditDatabaseName.Text + ".sdf";
if (File.Exists(fileName))
{
MessageBox.Show("Database with this name already existed at this location !", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
string connectionString;
string password = "123";
connectionString = string.Format(
"DataSource=\"{0}\"; Password='{1}'", fileName, password);
SqlCeEngine en = new SqlCeEngine(connectionString);
en.CreateDatabase();
}

Related

Visual studio app.config file database path for installed apps

I am using local database in my app and when I generate installation file (By Installer Package), after installing program it gives database path errors.
Eample
an attempt to attach an auto-named database for file....
//OR
The given path format is not supported
I've tried to edit database path in app.config file but it failed every time, By default my code line is like this:
<add name="SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SampleDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
And my app installing in C:\Program Files (86)\App_Folder\Setup Please note that future users might install it in custom path so I need a way to get dynamic path of installed app.
My question is How can I get app installed path to replace with this part AttachDbFilename=|DataDirectory|\SampleDatabase.mdf?
You could try to use AppDomain.CurrentDomain.SetData method to change your mdf file path.
Since, I don't know how do you published the winform project.
I recommend that you use Clickonce to publish it.
First, please include your mdf file in your project.
Second, you could try the following code to change the installed path after you published it.
private void Form1_Load(object sender, EventArgs e)
{
if(System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
string path = ApplicationDeployment.CurrentDeployment.DataDirectory; //Get installed path
AppDomain.CurrentDomain.SetData("DataDirectory", path);//set the DataDirectory
}
}
Finally, based on my test, I can get the information from the mdf file after I publised it and installed it in another computer.
In production mode |DataDirectory| refers to 'bin' directory, not 'app_data'. If you placed the .mdf file in the app_data directory, you can change it like this:
|DataDirectory|\SampleDatabase.mdf to |DataDirectory|\app_data\SampleDatabase.mdf
<add name="SampleDatabaseWalkthrough.Properties.Settings.SampleDatabaseConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\app_data\SampleDatabase.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
Update1:
I'm sending some code. I just want to give you an idea. You can change it for your situation.
private void Form1_Load(object sender, EventArgs e)
{
if (!IsExist())
{
CreateDatabase();
CreateTables();
}
}
// Create the Database
private void CreateDatabase()
{
string basePath = Environment.CurrentDirectory;
string mdfFile = "TestDatabase.mdf";
string ldfFile = "TestDatabase_Log.mdf";
string mdfFullPath = System.IO.Path.Combine(basePath, "Data", mdfFile);
string ldfFullPath = System.IO.Path.Combine(basePath, "Data", ldfFile);
SqlConnection myConn = new SqlConnection("Server=.;Data Source=(LocalDB)\\MSSQLLocalDB;Integrated security=SSPI;database=master");
string str = "CREATE DATABASE TestDatabase ON PRIMARY " +
"(NAME = TestDatabase, " +
$"FILENAME = '{mdfFullPath}', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)" +
"LOG ON (NAME = MyDatabase_Log, " +
$"FILENAME = '{ldfFullPath}', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
// Create the tables and other stuff that you want
private void CreateTables()
{
string conStr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data\TestDatabase.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection myConn = new SqlConnection(conStr);
string str = #"CREATE TABLE [dbo].[TestTable]
(
[Id] INT NOT NULL PRIMARY KEY,
[Test] NVARCHAR(50) NULL
)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
// Check if there is the database
private bool IsExist()
{
string basePath = Environment.CurrentDirectory;
string mdfFile = "TestDatabase.mdf";
string mdfFullPath = System.IO.Path.Combine(basePath, "Data", mdfFile);
return System.IO.File.Exists(mdfFullPath);
}

Connection string for local database in C#

Maybe it's repetitive but I googled and didn't find my answer.
I developed a program by .net that has a local database (Express) that works excellently on my computer, but when I create a setup and installation, it can't insert or update and so on for example in Delete() method I have
try
{
}
catch
{
}
in the exefile always goes to the catch{} section and I don't know why :((
This is my connection string:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;Connect Timeout=30
This is one of my methods for example:
private Boolean Delete(int id)
{
//String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Parnian\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(Connection);
String sqll = "Delete FROM TblBank WHERE Id =#id ";
try
{
sql.Open();
SqlCommand cmd = new SqlCommand(sqll, sql);
cmd.Parameters.AddWithValue("id", id);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
sql.Close();
return true;
}
catch (Exception ex)
{
MessageBoxEx.Show("have some problem", "wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
and Necessary say i put my .mdf and .ldf file into my setup folder and make setup by Visual Studio Installer
Try this
private bool Delete(int id)
{
string connString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Parnian\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sqlConn = new SqlConnection(connString);
String sql = "Delete FROM TblBank WHERE Id =#id ";
try
{
sqlConn.Open();
SqlCommand cmd = new SqlCommand(sql, sqlConn);
cmd.Parameters.AddWithValue("id", id);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
sql.Close();
return true;
}
catch (Exception ex)
{
MessageBoxEx.Show(ex.Message, "wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
So that you can see what the error is. At the moment you are just saying something went wrong when ex contains everything you will need to debug the problem.
Hope this helps.
(There are a few things to refactor too, such as wrapping your connection in a using statement.)
The cause of your problem is very simple. There can be two situations in your case. They are as follows:
The computer you are trying to run the application doesn't have the proper version of the sql server.
Solution: In this case, you have to find out in which sql server version you have created your database. Then you have to include that version of sql server into the setup.exe package. So that when the setup.exe executes the proper sql server also setups with your application.
The computer you are trying to setup the application has proper sql version but still you are getting the error.
Solution: First delete your existing database and create new database from solution explorer.Then use this particular connection string given below
SqlConnection conn = new
SqlConnection (global::ProjectName.Properties.Settings.Default.ProjectConnectionString);
ProjectConnectionString can be found in App.config file after you connect your database to your solution.
Hope this helps. Feel free to ask in the comment if you need to.
#Parnian It should required to install local db in your system.
1.when you click server object explorer and then when you click on Localdb server you will get proper connection string from properties .
enter code here static void Main(string[] args)
{
TestConncetion testConncetion = new TestConncetion(Delete);//here I used delegate
WriteLine($"My connection string is working Fine ,result is {testConncetion(1)}");
}
private static bool Delete(int id)
{
string Connection = #"Data Source=(localdb)\ProjectsV13;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
//String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Parnian\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(Connection);
string sqll = "Delete FROM TblBank WHERE Id =#id ";
try
{
sql.Open();
SqlCommand cmd = new SqlCommand(sqll, sql);
cmd.Parameters.AddWithValue("id", id);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
sql.Close();
return true;
}
catch (Exception ex)
{
WriteLine("have some problem", "wrong", ex.Message);
return false;
}
}

How to backup the database from the server to the client computer using asp.net page

I have used code C # to write one page of data to back up the .bak file from the server to the client machine. when I tested on my computer is very good. which when connected through another computer by using connectionString web.cofig it reappears errors like this. This one was like before or workaround, please help.
private string _ConnectionString = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FillDatabases();
//ReadBackupFiles();
}
}
private void FillDatabases()
{
try
{
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = _ConnectionString;
sqlConnection.Open();
string sqlQuery = "SELECT * FROM sys.databases";
SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
sqlCommand.CommandType = CommandType.Text;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
DataSet dataSet = new DataSet();
sqlDataAdapter.Fill(dataSet);
ddlDatabases.DataSource = dataSet.Tables[0];
ddlDatabases.DataTextField = "name";
ddlDatabases.DataValueField = "database_id";
ddlDatabases.DataBind();
}
catch (SqlException sqlException)
{
lblMessage.Text = sqlException.Message.ToString();
}
catch (Exception exception)
{
lblMessage.Text = exception.Message.ToString();
}
}
protected void btnBackup_Click(object sender, EventArgs e)
{
try
{
string _DatabaseName = ddlDatabases.SelectedItem.Text.ToString();
string _BackupName = _DatabaseName + "_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + ".bak";
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = _ConnectionString;
sqlConnection.Open();
string sqlQuery = "BACKUP DATABASE " + _DatabaseName + " TO DISK = 'D:\\SQLServerBackups\\" + _BackupName + "' WITH FORMAT, MEDIANAME = 'Z_SQLServerBackups', NAME = '" + _BackupName + "';";
SqlCommand sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
sqlCommand.CommandType = CommandType.Text;
int iRows = sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
lblMessage.Text = "The " + _DatabaseName + " database Backup with the name " + _BackupName + " successfully...";
ReadBackupFiles();
}
catch (SqlException sqlException)
{
lblMessage.Text = sqlException.Message.ToString();
}
catch (Exception exception)
{
lblMessage.Text = exception.Message.ToString();
}
}
You create backup in online-mode or just have in your server? If you have some files in your server, realize downloading function and that's all what you need.
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename="+file);
Response.TransmitFile(Server.MapPath("~/backups/"+file)); //backup must be located in folder in your application folder, that folder named *backups*
Response.End(); //file is a filename of your backup: e.g. 20151224.bak
If you create backup online and want to send it to user, you have to do next steps (it is just one approach):
1) Make backup and save it into your application folder to some temporary folder
2) Realize download page as I show earlier (user will download it)
3) And as soon as user download that, you will just delete your temporary backup file.
Hope it helps
What is happening is when you run this program on your computer everything works right because it's setup for your system. If you want to transfer to your system or another computer separate from the server there are a couple of things that might work. You can make a shared drive off the system you want the program to drop the files in, which may or may not work since share folders are treated differently then normal folders/drives. I would write a upload program that connects to a file server and uploads the backup files to there automatically, after the server dumps to a predefined folder that the server has access to. There are some really good file upload libraries available to C# that can automate this process for you. So you can have an asp.net page that puts the backup file like it does for your system currently, and another c# program that is setup to run at a certain time using scheduler and uploads the backup to your desired location remotely from the server.
Hope this makes sense, let me know if you have any questions.
https://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx
Here is the code to have C# upload files automatically for you from a file location. You'll need to setup a ftp server on the computer you want the backups to go to. Otherwise the only way around this is to make the files available for download off the sever in question which means just making the folder visible to the Internet. But I'd go with the ftp options since it's the most flexible.

Code to create & connect to a SQL Server database: Whats wrong with it?

I am new to C# & I am trying to programatically create & open a SQL Server database.
I have a ASP.NET webapp I am creating & on page load it should pull some data from the database (if the db doesn't exist, it should be created & populated with default data).
PS: does C#'s System.Data.SqlClient use MySQL or SQLite or something else?
Right now I am unsure if my code correctly creates a SQL Server database & if I connect to it correctly.
Can you tell me if my code is correct & how I could improve it?
UPDATE: Error is
"A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: Named
Pipes Provider, error: 40 - Could not open a connection to SQL
Server)"}"
I have indicated where in the code below the error occurs.
Creating a SQL Server database:
// When I run this function no file seems to be created in my project directory?
// Although there is a ASPNETDB sql database file in my App_Data folder so this maybe it
public static string DEF_DB_NAME = "mydb.db"; // is this the correct extension?
private bool populateDbDefData()
{
bool res = false;
SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master");
string str = "CREATE DATABASE "+DEF_DB_NAME+" ON PRIMARY " +
"(NAME = " + DEF_DB_NAME + "_Data, " +
"FILENAME = " + DEF_DB_NAME + ".mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = " + DEF_DB_NAME + "_Log, " +
"FILENAME = " + DEF_DB_NAME + "Log.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open(); // ERROR OCCURS HERE
myCommand.ExecuteNonQuery();
insertDefData(myConn);
}
catch (System.Exception ex)
{
res = false;
}
finally
{
if (myConn.State == ConnectionState.Open)
myConn.Close();
res = true;
}
return res;
}
Here's my connection to the SQL Server database code: I am pretty sure it fails to connect - if I try to use the variable conn, it says the connection is not open. Which could mean that I either failed to connect or failed to even create the db in the 1st place:
private bool connect()
{
bool res = false;
try
{
conn = new SqlConnection("user id=username;" +
"password=password;" +
"Server=localhost;" +
"Trusted_Connection=yes;" +
"database="+DEF_DB_NAME+"; " +
"connection timeout=30");
conn.Open();
return true;
}
catch (Exception e)
{
}
return false;
}
You have probably already got this figured out, but just in case people end up here with the same problem (like I did) here's how I got this working.
Your error is that the SqlConnection is not being opened, because it isn't finding an appropriate server. If you're using the SQL server express edition (as I am) you should set the SqlConnection object like this:
SqlConnection myConn = new SqlConnection("Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=master;");
Once you resolve that error though, you are going to fail on the next line when you try to execute the query. The "Filename" needs to be separated by single quotes, but you only have one on the end after the extension; you will also need one before.
Also, that is the full physical file path, and it won't use the current directory context, you have to specify a path. Make sure that the location is one which the db server will have access to when it's running, otherwise you will get a SqlException being thrown with an error message along the lines of:
Directory lookup for the file "...\filename.mdf" failed with the operating system error 5 (Access is denied). CREATE DATABASE failed. Some file names listed could not be created.
The code which I ended up using looks like this:
public static string DB_NAME = "mydb"; //you don't need an extension here, this is the db name not a filename
public static string DB_PATH = "C:\\data\\";
public bool CreateDatabase()
{
bool stat=true;
string sqlCreateDBQuery;
SqlConnection myConn = new SqlConnection("Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=master;");
sqlCreateDBQuery = " CREATE DATABASE "
+ DB_NAME
+ " ON PRIMARY "
+ " (NAME = " + DB_NAME + "_Data, "
+ " FILENAME = '" + DB_PATH + DB_NAME + ".mdf', "
+ " SIZE = 2MB,"
+ " FILEGROWTH = 10%) "
+ " LOG ON (NAME =" + DB_NAME + "_Log, "
+ " FILENAME = '" + DB_PATH + DB_NAME + "Log.ldf', "
+ " SIZE = 1MB, "
+ " FILEGROWTH = 10%) ";
SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception)
{
stat=false;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
myConn.Dispose();
}
return stat;
}
Use this code,
internal class CommonData
{
private static SqlConnection conn;
public static SqlConnection Connection
{
get { return conn; }
}
public static void ReadyConnection()
{
conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString();
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
}
public static int ExecuteNonQuery(SqlCommand command)
{
try
{
ReadyConnection();
command.Connection = conn;
int result = command.ExecuteNonQuery();
return result;
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Dispose();
if (conn.State == ConnectionState.Open) conn.Close();
conn.Dispose();
}
}
public static SqlDataReader ExecuteReader(SqlCommand command)
{
try
{
ReadyConnection();
command.Connection = conn;
SqlDataReader result = command.ExecuteReader(CommandBehavior.CloseConnection);
return result;
}
catch (Exception Ex)
{
throw Ex;
}
}
public static object ExecuteScalar(SqlCommand command)
{
try
{
ReadyConnection();
command.Connection = conn;
object value = command.ExecuteScalar();
if (value is DBNull)
{
return default(decimal);
}
else
{
return value;
}
}
catch (Exception ex)
{
throw ex;
}
}
public static void ClearPool()
{
SqlConnection.ClearAllPools();
}
}
PS: does C#'s System.Data.SqlClient use MySQL or SQLite or something else?
MySQL provides their own C# dll for connecting to their database, as do the majority of other database manufacturers. I recommend using theirs. I typically using the built-in SQL client for MS SQL (I am not aware if it can be used with other DBs).
As for this line: insertDefData(myConn) -> the method is not included in your code sample.
As for SQL debugging in general, use the GUI for debugging. I know a lot of people who grew up on MySQL do not want to, or do not understand why you should use one, but it's really a good idea. If you are connecting to MySQL, I recommend MySQL WorkBench CE; if you are connecting to a MS database, SQL Management Studio is what you want. For others, GUIs should be available. The idea here is that you can selectively highlight sections of your query and run it, something not available via command-line. You can have several queries, and only highlight the ones you want to run. Plus, exploring the RDBMS is easier via a GUI.
And if you want to prevent a SQL injection attack, just Base64 encode the string data going in.
As for the connection string itself, we will need some more data on what type of database, exactly, you are trying to connect to. Personally, I recommend just creating a separate SQL account to handle operations (easier to track, and you only need to give it permissions to what you want it to access; security and all that).

Connection string and sql backup

I'm having problem with the following C# code to perform a backup, particularly in the connection string.
The code is as follows:
private void BK()
{
string strconn = #"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strconn;
try {
//Query per backup
string queryBK = "BACKUP DATABASE db TO DISK ='C:\\Program Files\\Microsoft SQLServer\\MSSQL10.SQLEXPRESS\\MSSQL\\Backup\\db.bak' WITH INIT, SKIP, CHECKSUM";
SqlCommand cmdBK = new SqlCommand(queryBK, conn);
conn.Open();
cmdBK.ExecuteNonQuery();
MessageBox.Show("backup effettuato");
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "ERRORE", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally {
conn.Close();
}
}
This code works on the development PC, but if I install my application on another PC it throws this error:
The database does not exist. Verify that the name has been entered
correctly. INTERRUPTION ANOMALOUS BACKUP DATABASE.
I would stress that this string works well with the operations INSERT, DELETE, UPDATE
on both my PC and on the PC test.
If I replace the connection string with:
string strconn = #"Data Source=.\SQLEXPRESS; Database = db;Trusted_Connection =True";
The string works on my dev machine but not on the test machine. It throws the following error:
Can not open database requested by the login. Login failed. Login
failed for user Pina-PC \ Pina
Dear fellow you can use your code in this way.
private void BK()
{
string strconn = #"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strconn;
try {
// First get the db name
conn.Open();
string dbname;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
dbname = cmd.Connection.Database.ToString();
//Query per backup
string queryBK = "BACKUP DATABASE " + dbname + " TO DISK ='C:\\Program Files\\Microsoft SQLServer\\MSSQL10.SQLEXPRESS\\MSSQL\\Backup\\db.bak' WITH INIT, SKIP, CHECKSUM";
SqlCommand cmdBK = new SqlCommand(queryBK, conn);
conn.Open();
cmdBK.ExecuteNonQuery();
MessageBox.Show("backup effettuato");
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "ERRORE", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally {
conn.Close();
}
}
this routine will work in your case.

Categories