title: How To Restore .mdf File After Backup C#
body: <p>How to restore a database from a <code>.mdf</code>?</p>
  <p>I wrote a <code>.mdf</code> to <code>.bak</code> method and the code worked correctly
  but when I wrote a restore method it did not work.</p>
  <p>My code:</p>
  <pre class="lang-cs prettyprint-override"><code>private void restoreButton_Click(object sender, EventArgs e)
  {
      try
      {
          OpenFileDialog op = new OpenFileDialog();
          op.Filter = &quot;نسخة احتياطية من قاعدة البيانات|*.bak&quot;;
          op.Title = &quot;اختر مكان النسخة الاحتياطية&quot;;
          // op.FileName = DateTime.Now.ToString(&quot;[yyyy-dd-M]-[HH-mm-ss]&quot; + &quot;  &quot; + &quot;  &quot; + &quot;نسخة بتاريخ&quot;);
  
          if (op.ShowDialog() == DialogResult.OK)
          {
              using (SqlConnection Sql_Conn = new SqlConnection(ConfigurationManager.ConnectionStrings[&quot;MyConn&quot;].ConnectionString))
              {
                  string file = string.Format(&quot;backup database [&quot; + System.Windows.Forms.Application.StartupPath + &quot;\\Car_Database] to disk='{0}'&quot;, op.FileName);
                  string constring = &quot;server=localhost;port3306;user=root;pwd=root;Car_Database=sms; Convert zero Datatime=true;&quot;;
                  using (MySqlConnection conn = new MySqlConnection(constring))
                  {
                      using (MySqlCommand cmd = new MySqlCommand())
                      {
                          using (MySqlBackup mbak = new MySqlBackup(cmd))
                          {
                              cmd.Connection = conn;
                              Sql_Conn.Open();
                              mbak.ImportFromFile(file);
                              Sql_Conn.Close();
  
                              MessageBox.Show(&quot;تمت عملة النسخ بنجاح&quot;);
                          }
                      }
                  }
              }
          }
      }
      catch (Exception)
      {
          MessageBox.Show(&quot;عذراً . لقد حدث خطأ ما اثناء قيامك بعمل نسخة من قاعدة البيانات , الرجاء المحاولة مرة اخرة&quot;);
      }
  }
  </code></pre>