如何备份LocalDB C#我的数据库文件名为MyDatabase.mdf

问题描述:

string dbpath= System.Windows.Forms.Application.StartupPath;
             string dbp = dbpath + "\\MyDatabase.Mdf";

SqlCommand cmd = new SqlCommand("backup database ['"+dbp+"'] to disk ='d:\\svBackUp1.bak' with init,stats=10",con);

cmd.ExecuteNonQuery();

错误是以----开头的标识符太长.最大长度为128" 所以我用小名字"MyDb.mdf"来制作"MyDatabase.mdf".这样标识符就小于128.

Error was that "The identifier start with---- is too long. Maximum length is 128" so I Make the "MyDatabase.mdf" with small Name "MyDb.mdf".So the identifier becomes less than 128.

我的代码是

 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NewConnectionString"].ConnectionString);

 {
con.Open();

  string DatabaseName = Application.StartupPath + @"\MyDb.mdf";

SqlCommand cmd = new SqlCommand("BACKUP DATABASE ["+DatabaseName+"] to DISK='D:\\MyBackup.bak' ", con);


            try
            {
                cmd.ExecuteNonQuery();
                MessageBox.Show("Success");
            }
            catch (Exception Ex){
                MessageBox.Show("'"+Ex.ToString()+"'");
            }
            con.Close();

}


成功获取备份


successfully take the Backup