Click here to Skip to main content
15,877,168 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
Hello All

I have generated an windows application. I have used .MDF file.
The project is working fine but I want to backup my .Mdf file on a button click. When i copy this file from bin folder tuser location then it gives an error
like 'The process cannot access the file '.mdf' because it is being used by another process'.

What code should i use/ technique should i use so I can do so.

I am using :

Visual Studio 2010,
dot net framwork 3.5 sp1
MDF FILE of Microsoft Sql server 2005.

Here is the coding
con="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Test.mdf;Integrated Security=True;User Instance=True"

 SaveFileDialog SaveFD1 = new SaveFileDialog();
 string FileName = "";
 SaveFD1.FileName = "Test";
 SaveFD1.Title = "Backup ";
 SaveFD1.Filter = "Database files (*.mdf)|*.mdf";
 SaveFD1.FilterIndex = 1;
 SaveFD1.DefaultExt = "mdf";
 SaveFD1.RestoreDirectory = true;
 if (SaveFD1.ShowDialog() == DialogResult.OK)
    FileName = SaveFD1.FileName
    string sourcePath = Application.StartupPath;
    string src = sourcePath + "\\Test.mdf";
    string dst = path;                   
    System.IO.File.Copy(src, dst, true);
Updated 18-Jan-15 19:16pm

Here is the solution. I found it from many days googled..
    SaveFileDialog sd = new SaveFileDialog();
    sd.Filter = "SQL Server database backup files|*.bak";
    sd.Title = "Create Database Backup";

    if (sd.ShowDialog() == DialogResult.OK)
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["project_name.Properties.Settings.project‌​_nameConnectionString"].ConnectionString))
            string sqlStmt = string.Format("backup database [" + System.Windows.Forms.Application.StartupPath + "\\dbname.mdf] to disk='{0}'",sd.FileName);
            using (SqlCommand bu2 = new SqlCommand(sqlStmt, conn))

                MessageBox.Show("Backup Created Sucessfully");
catch (Exception)
    MessageBox.Show("Backup Not Created");
Share this answer
You don't take a backup by copying an active MDF file (or any other database file). Because of the buffering mechanisms the data may be in inconsistent state.

Instead, use the BACKUP[^] statement to get a consistent backup somewhere and then copy that file to a safe location.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900