Search code examples
fileinfodirectoryinfo

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


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?


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.