-2

I have two files (.mdf and .ldf) in the App_Data folder. Now I want to copy these 2 files and need to paste into backup folder while running the application. But I'm getting an error:

The process cannot access the file 'D:\App_Data\' because it is being used by another process.

These is my code I've been using

string dir = Directory.GetDirectories(@"D:\","App_data").FirstOrDefault();
string targetPath = @"D:\Back_up_PayRoll\";

if (System.IO.Directory.Exists(dir))
{
    string[] files = System.IO.Directory.GetFiles(dir);

    if (!Directory.Exists(targetPath))
        Directory.CreateDirectory(targetPath);

    foreach (string s in files)
    {
        var fileName = System.IO.Path.GetFileName(s);

        var destFile = System.IO.Path.Combine(targetPath, fileName);
        System.IO.File.Copy(s, destFile, true);
        MessageBox.Show("BACK-UP Done..");
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Use Volume Shadow Copy : https://en.wikipedia.org/wiki/Shadow_Copy – aybe Jan 02 '16 at 08:50
  • Then How to Stop the process of file is being used by Another Application – Fernando Sucre Jan 02 '16 at 08:50
  • 1
    Sounds like an [XY Problem](http://meta.stackexchange.com/a/66378/161449). What are you *actually* trying to do? Why do you need to copy your database files while they are in use by your own application? – Andrew Savinykh Jan 02 '16 at 09:17
  • yes @ zespri, I need to copy those files as backup – Fernando Sucre Jan 02 '16 at 09:18
  • @FernandoSucre then either stop the database (gracefully, not killing the process), or use shadow copy. Killing the database process which may be writing to it at the time is definitely **NOT** a good idea. Killing a stuck process as an emergency measure is one thing. Killing it routinely just because it's locking a file is not. Locks exist for a reason – Jcl Jan 02 '16 at 09:19
  • 3
    Those are **SQL Server** data and transaction log files - **DO NOT** just simply copy those! Use the proper SQL Server `BACKUP DATABASE` command to back up a SQL Server database! – marc_s Jan 02 '16 at 09:24
  • As mark_s says, copying files is NOT how you back up a database. *This* is why it's important, that you explain what you are actually trying to do, as you already have. You were trying to solve a wrong problem. – Andrew Savinykh Jan 02 '16 at 10:25

2 Answers2

0

If available on the system, you could use a snapshot using the Volume Shadow Copy Service

From C#, there's the handy AlphaVSS library that wraps the COM interface, but you could implement it directly.

If VSS is not available, then tough luck, no way around a file lock

PS: of course, this ain't as easy as File.Copy

Jcl
  • 27,696
  • 5
  • 61
  • 92
0

You cannot access an MDF file in any way without disconnecting from it first.

Best bet is backing it up using SQL, or shutting down your application and copying it by running a BAT file

Robert
  • 642
  • 7
  • 11