Search code examples
c#directorycopytarget

Copying files into newly created folder giving error "its being used by another process


I try to create a sub-application that copies the database to the user desired location. Although an error is popping up that my newly created folder is being used by another application (i havent used any stream readers).

The files are correct and the copy to the selected directory is totaly working , although the problem starts when i create the folder and after i try to use him.

//Snippet
string SourceFile1 = @"C:\Users\user\Documents\DLLTESTBASE.mdf";
string SourceFile2 = @"C:\Users\user\Documents\DLLTESTBASE_log.ldf";
string BackupDirectory = BackupLocation.SelectedPath + "\\" + BackupName;
if (!Directory.Exists(BackupDirectory)){
    Directory.CreateDirectory(BackupDirectory);
    }
else{
     MessageBox.Show("A copy has been found :\n" + BackupDirectory , "Copy has been stoped!");
    }

string targetPath1 = BackupDirectory + "\\DB.mdf"; 
string targetPath2 = BackupDirectory + "\\DB_log.ldf";

try{
     System.IO.File.Copy(SourceFile1, targetPath1);
     System.IO.File.Copy(SourceFile2, targetPath2);
     MessageBox.Show("Copy has been successful.", "Completed!");
    }
catch (Exception ex){
    MessageBox.Show("An error has been occured."+ex,"Operation failed!");}
    }

The result must be that the 2 files will be inside of the folder.


Solution

  • Sql Data Base File in use with Sql Service

    Goto Services

    Stop "Sql Server" Service

    you can use this link stop-or-start-sql-server-service

    If u dont want to stop service use this link

    Also u can use Attaching-and-Detach DB PragmaticallyAttaching-and-Detach