Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory.Exists hold directory handle for several seconds

Tags:

c#

windows

So I am trying to Unit test/Integration test my code responsible for sharing a directory.

So I create my share drive and then I check if the directory exists. First locally and then via it's share name.

Assert.IsTrue(Directory.Exists(testSharePath));
Assert.IsTrue(Directory.Exists(
    String.Format(@"\\{0}\{0}", System.Environment:MachineName, testShareName));

After this I of course want to clean up after myself by removing the directory I just created. However this does not work because "...it is used by another process."

After some experimenting I found that if I remove my second Assert it works again. Am I doing something wrong? Oh, and I also noticed that if I put a 30 second sleep in there before removing the directory it also works. Wtf?

EDIT: I just revisited this issue and tried as people been suggesting in the comments to unshare the folder explicitly first. That was it. Worked like a charm.

like image 973
jimmy Avatar asked Mar 23 '15 17:03

jimmy


1 Answers

As requested by @DWright I will answer my own question since no one else did, for documentation purpose and for clarity if other people find this post.

My problem was solved by explicitly unsharing the folder before removing it:

var share = String.Format("Win32_Share.Name='{0}'", shareName);
var managementObj = new ManagementObject(share);
managementObj.InvokeMethod("Delete", null, null);
like image 91
jimmy Avatar answered Sep 18 '22 14:09

jimmy