Hi
What is wrong in my this backup code it always not working and gives me an error

 SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;
                                     AttachDbFilename=D:\repos\mysales\WindowsFormsApp4\Database1.mdf;
                                     Integrated Security=True;
                                     ");
 string database = con.Database.ToString();
 if (textBox1.Text == "") 
 {
     MessageBox.Show("Please Enter Backup File Location");
 }
 else
 {
     string cmd = "BACKUP DATABASE [" + database +"] To DISK = '"+ textBox1 .Text + " \\ " +"database"+"-"+ DateTime .Now .ToString ("yyyy-MM-dd--HH-mm-ss") +".bak'";
     con.Open();
     SqlCommand  command=new SqlCommand(cmd, con);
     command.ExecuteNonQuery();
     MessageBox.Show("Database Backup Done Seccessfully.");
     con.Close();
     button2.Enabled = false;
 }

THis is the error

System.Data.SqlClient.SqlException: 'An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.'

By the way I am using sql server that bult-in in Visual Studio

  1. Run the program in the debugger.
  2. Put a breakpoint on con.Open();
  3. Run the backup part of the program.
  4. Print the contents of the cmd string, after it's made all the runtime substitutions.

Is that string what you were expecting?

The spaces around your double-back-slash seem out of place.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.