I want to copy a folder, and i want to delete destination folder first. So I am deleting destination folder then recreate it and then copy files. The problem is that i get the <
You got it kinda wrong. The reason for the exception is that there's still a resource that is accessing the folder (or file).
The solution is never GC.collect()
or Sleep()
... That's just a work around.
What you're doing is just letting the garbage collector dispose of the resource, and then giving it time to act.
The RIGHT way is to manage your own resources. Instead of a static method that you have no control on, use a using
block and dispose of the resource in the end of the block. This way there's no overhead while your waiting for things that aren't under your control (GC).
Use an object that controls the resources, and the using
block will dispose it at the end.
In your case, using a single DirectoryInfo
object that controls that resource should work.