1

I am building a winform based Desktop application in C#. I am using SQL Server Database in my application.

The application has an option of taking an archive, where I basically copy all the configuration files and data files ( *.mdf) into a Winzip Archive.

However, I am not able to copy the Database file *.mdf. It throws an exception :

"The process cannot access the file UserData.mdf because it is being used by another process"

I believe I am closing all the SQL connection, and perform manual Garbage collection via GC.Collect().

But, this doesn't seem to work.

As a workaround, if I am able to kill the process sqlservr.exe from the Taskmanager, the file copy works fine.

I guess, there should be a better and a more elegant way of doing it. Any Idea how to proceed ?

Thanks Kiran

5
  • 1
    You should create a backup of the database instead of trying to copy the mdf file. You can have a look here for a short example: codeproject.com/Tips/461494/… Jan 11, 2013 at 13:08
  • 1
    The mdf data file will be locked by the SQL Server process & may not represent the true state of the database at a point in time (buffer cache et al) you need to use its built in backup functionality stackoverflow.com/questions/5871302/… (or detach it first which would flush & offline it)
    – Alex K.
    Jan 11, 2013 at 13:08
  • Keep your hands off GC. Jan 11, 2013 at 13:11
  • 1
    Unless you provide us the code we can't determine the cause of this error. Clearly something is using the file in question if your getting this error. Sounds like you should perform use the built-in features of SQL Server to generate the backup current state of the database. Jan 11, 2013 at 13:50
  • I just modified the code to take the Backup via Backup Script as proposed by @Yakyb
    – Kiran
    Jan 11, 2013 at 15:50

1 Answer 1

5

i'm not sure entirely what you are trying to do with this, but it sounds as though a backup script would be far more beneficial

http://msdn.microsoft.com/en-us/library/ms187510.aspx

BACKUP DATABASE [AdventureWorks2012]
TO DISK = 'd:\AdventureWorks2012.Bak'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.