I am a little less new to programming than I was a week ago, I had some great help on getting a problem point I was stuck on taken care of. I am hoping for some luck this go around as well. I created a form with a button that backups SQL databases, I wanted to add a start and stop to the MSSQLSERVER service, and I believe I have this working properly. The only thing is it flashes on the screen so fast I can not confirm (I know more for my peace of mind than anything) if it actually stops and starts. Here is my code so far:
private void Backup_Click(object sender, EventArgs e)
{
string root = @"C:\Tools";
// If directory does not exist, create it.
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source= localhost; Initial Catalog= Local;Integrated Security=True;";
string database = con.Database.ToString();
try
{
{
string cmd = "BACKUP DATABASE [" + database + "] TO DISK='" + @"C:\Tools" + "\\" + "Local" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'";
using (SqlCommand command = new SqlCommand(cmd, con))
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("database backup done successefully");
System.Diagnostics.Process.Start("net", "stop MSSQLSERVER").WaitForExit();
System.Diagnostics.Process.Start("net", "start MSSQLSERVER").WaitForExit();
}
}
}
catch
{
}
}
I appreciate any and all help.
I just wanted to add this worked for me in case anyone else ever needs it:
private void Backup_Click(object sender, EventArgs e)
{
string root = @"C:\Tools";
// If directory does not exist, create it.
if (!Directory.Exists(root))
{
Directory.CreateDirectory(root);
}
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source= localhost; Initial Catalog= Local;Integrated Security=True;";
string database = con.Database.ToString();
try
{
{
string cmd = "BACKUP DATABASE [" + database + "] TO DISK='" + @"C:\Tools" + "\\" + "Local" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak'";
using (SqlCommand command = new SqlCommand(cmd, con))
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("database backup done successefully");
ServiceController service = new ServiceController("SQL Server (MSSQLSERVER)");
service.Stop();
MessageBox.Show("SQL Server was stopped successfully");
System.Threading.Thread.Sleep(5000);
service.Start();
MessageBox.Show("SQL Server was restarted successfully");
}
}
}
catch (Exception ex)
{
MessageBox.Show($"error occurred: {ex.ToString()}");
}
}
```
Thanks for all the help.