Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backing up Database in MySQL using C#

Tags:

c#

mysql

winforms

I created a Winforms in order to backup my Database. Then When I run my program it gives an Win32Exception was unhandled. "The system cannot find the file specified" Although the file is already existed and resulted to that exception.

Here is my code regarding my problem

using System.Diagnostics;

private void btnProceed_Click(object sender, EventArgs e)
{
            path = @"D:\MySQL\MySQL Server 5.5\bin\mysqldump.exe -u " + txtBoxDBUsername.Text + @" -p " + txtBoxDBName.Text + @" > D:\C#\Client\Salesmate - EMC\SalesMate\Backup\" + maskeTxtBoxDBFile.Text + @"";
            Process p = new Process();
            p.StartInfo.FileName = path;
            p.Start();
}
like image 258
Bon Avatar asked Sep 07 '12 03:09

Bon


1 Answers

You can use MySqlBackup.NET as alternative to MySqlDump
Documentation:
http://www.codeproject.com/Articles/256466/MySqlBackup-NET-MySQL-Backup-Solution-for-Csharp-V
https://github.com/MySqlBackupNET/MySqlBackup.Net

Sample codes:

Backup a MySQL database

using MySql.Data.MySqlClient; 

then the code,

private void Backup()
{
    string constring = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\backup.sql";
    using (MySqlConnection conn = new MySqlConnection(constring))
    {
        using (MySqlCommand cmd = new MySqlCommand())
        {
            using (MySqlBackup mb = new MySqlBackup(cmd))
            {
                cmd.Connection = conn;
                conn.Open();
                mb.ExportToFile(file);
                conn.Close();
            }
        }
    }
}


Restore a MySQL database

private void Restore()
{
    string constring = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\backup.sql";
    using (MySqlConnection conn = new MySqlConnection(constring))
    {
        using (MySqlCommand cmd = new MySqlCommand())
        {
            using (MySqlBackup mb = new MySqlBackup(cmd))
            {
                cmd.Connection = conn;
                conn.Open();
                mb.ImportFromFile(file);
                conn.Close();
            }
        }
    }
}

Update:
I am one of the author of this library.

like image 55
mjb Avatar answered Oct 11 '22 00:10

mjb