Can certain File.IO objects in .NET (like DirectoryInfo) keep a removable device referenced even after programm termination

StackOverflow https://stackoverflow.com/questions/1284640

  •  18-09-2019
  •  | 
  •  

Question

I have written a program in .NET that recurses through all files of a source and destination directory and its subdirectories, compares lastwritetime and copies/deletes files to/from the destination directory based upon comparison result.

When eg. the destination directory is a directory on a removable drive (usb), I can not remove the usb drive from my pc, even after the program is closed. There are no other programs that have the usb open (eg explorer) and the program does not appear in the task list anymore.

The program works by getting DirectoryInfo for each directory and subdirectories using

DirectoryInfo dir = new DirectoryInfo(path);

I use GetFiles to get all files:

var files =dir.GetFiles();

Then a foreach loops through all files to check for filtering out some files (done manually because I want multiple patterns using RegEx).

Files that are not excluded based on regex filters, are added to a SortedList, one for source dir, and one for destination dir.

This is used by the compare function. It creates an enumerator for the source list and one for the destination list using the using pattern:

using (var srcEnum = _srcFileInfos.GetEnumerator())
{
    using (var dstEnum = _dstFileInfos.GetEnumerator())
    {
       ... // compare code
    }
}

Finally, files are copy or deleted using

 File.Copy
 File.Delete

Is there something I'm overlooking in terms of memory management, that would keep references to the usb drive even after I close the program?

Was it helpful?

Solution

You may have closed the program, but check to make sure that the process has really terminated. Use Task Manager to find the process, then close it, then check with Task Manager to make sure it's really gone.

OTHER TIPS

You can use the free Unlocker utility to enumerate what locks exist on file object. Alternately, you can use Sysinternals' HANDLE.EXE to list all handles for all running processes.

I pretty much sure, that starting the program from usb, caused the locking of the usb device, although I do not understand why. Since I started running the program for local drive, I experienced no locks anymore. Maybe because its the debug version? Don't know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top