System.IO.DirectoryNotFoundException after deleting an empty folder and recreating it

后端 未结 7 2233
我在风中等你
我在风中等你 2021-02-13 04:37

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 <

7条回答
  •  南笙
    南笙 (楼主)
    2021-02-13 05:06

    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.

提交回复
热议问题