简体   繁体   中英

How to copy file from C#.Net

My C#.Net windows Application connects to a SQLServer2005 database and implements database backup functionality.

In my Application,

I try to perform a file copy like this:

<!-- language:lang-csharp -->
File.Copy(Application.StartupPath + "\\dbSTK.mdf",  "D:\\dbSTK123.mdf",true);

but it throws an exception with the following message:

" The Process cannot Access the File, because it is being use by another Process"

How can I copy the db file which is already in use?

You cannot copy mdf file while SqlServer is running. Just temporary shut SqlServer down or Detach that database ( here ) before copying.

Rather that copy the actual MDF, it's probably a better idea to backup the MDF using SQL Server's built in BACKUP command.

The suggestions to detach the database and then copy it are problematic because it takes your database offline.

The server denies inteprocess access to data files. Once it has opened a data file no other process can open one too. That's why your function fails.

You should close all open connections to DB to access the DB file. But generally, you should not touch the database file. You'd better use SQL command to back up the database.

string backupCommandText = "BACKUP DATABASE [<YOUR_DB_NAME>]" +
   "TO  DISK = N'<BACKUP_PATH>' WITH NOFORMAT, NOINIT, " + 
   "NAME = N'Web-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = backupCommandText ;
cmd.Connection = conn;  
cmd.ExecuteNonQuery();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM