Click here to Skip to main content
15,886,689 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
Cannot open backup device 'I:\aaa.bak'. Operating system error 32(The process cannot access the file because it is being used by another process.).

here my code

private void button_backup_Click(object sender, EventArgs e)
{
//con is the connection string
con.Open();
string str = "USE TestDB;";
string str1="BACKUP DATABASE TestDB TO DISK = 'E:\backupfile.Bak' WITH FORMAT,MEDIANAME = 'Z_SQLServerBackups',NAME = 'Full Backup of Testdb';";
SqlCommand cmd1 = new SqlCommand(str, con);
SqlCommand cmd2 = new SqlCommand(str1, con);
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
MessageBox.Show("success");
con.Close();
}
Posted
Updated 15-Aug-14 7:53am
v3
Comments
[no name] 15-Aug-14 9:12am    
You have to shutdown the process using the file.
mukesh mourya 15-Aug-14 9:25am    
sr here in my application i have option to create backup of database as button event then how can i do this please guide me ....help me
Mike Meinz 15-Aug-14 13:21pm    
You are not creating a backup in the code you provided. You are attempting to do a restore. You are trying to do a restore from a file ('I:\aaa.Bak') that is currently opened by another task. Maybe SQL Server Management Studio left it open? Or maybe some other process that created it left it open? Shut down those processes.

That said, it is rather dangerous to put a database restore button in your application. A user may restore the database and lose all of their transactions. Even if you train them, they could "mistakenly" do restore an old copy of the database.
mukesh mourya 15-Aug-14 13:54pm    
that my Improve question

1 solution

Database restoration is complex: because it destroys the current content of the DB.

In this case, I'd hazard a guess that your backup code is wrong, and is holding the file open - that would explain the "file in use" error you are getting, where very little else would.

Look at your backup code, and check it thoroughly: then try to use the restore.
There is an example of how I take backups here: Backing up an SQL Database in C#[^] which may help you.
 
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