简体   繁体   中英

How to copy mdf file into a folder with c#

I'm using c# and I have a small SQL Server database that I need to copy into a folder C:\\databases\\ , the method name is CreateCopy .

But at File.Copy row appear an error: "The Process cannot Access the File, because it is being use by another Process"

I read that File.Copy can be execute only after shut SqlServer down or Detach that database, create a copy and turn SqlServer on again. But how to do it by code?

This is the method that I was trying to use:

public static void CreateCopy()
{
    try
    {
        DateTime date = DateTime.Now;
        SqlConnection connection = new SqlConnection(MDF_CONNECTION_STRING);

        String dbpath = String.Format(@"C:\databases\{0:yyyyMMdd}.mdf", Cash, date);
        File.Copy(@"C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\database.mdf", dbpath);
        String lgpath = String.Format(@"C:\databases\{0:yyyyMMdd}_log.ldf", Cash, date);
        File.Copy(@"C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\database_log.ldf", lgpath);    
    }
    catch(Exception e)
    {
        throw new ApplicationException("Error", e);
    }
}

Thanks in advance!

INFO This is not a duplicate of here because i don't need to do create a bak file, i need to archive this database. I need just to copy these two files (.mdf and .ldf) into a folder. And that answers didn't help me

What I understand is that you are looking for the code which will help you to Programmatically Enumerating, Attaching, and Detaching SQL Server Databases So that you can copy the MDF file to the location. You can also have a look on How to Backup and Restore to get the idea of AttachDbFilename mode.

Database files .mdf and .ldf files are used by the SQL Server engine.

If you DETACH database from SQL Server instance, then you can copy or move those files.

But when you DETACH db, it will be unaccessible!

So it is better to run a backup command in SQL then use it.

Remove SqlConnection connection = new SqlConnection(MDF_CONNECTION_STRING); it will access the .mdf file and give it after the File.Copy() execute. because at the time of execution of File.Copy() the file is being used by SqlConnection that's because you are getting such error

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