Creating same new DirectoryInfo in loop?

  • Thread starter Vagabond Software
  • Start date
V

Vagabond Software

I am recursing through ALL folders and sub-folders below a certain level to list all the files of a certain type in those folders. I use two ArrayLists, alFiles and alFolders, to track matching files and my progress in the recursion.

I use a while loop to manage the folder-subfolder drill-down. Each pass through the while loop creates a new DirectoryInfo object named currentFolder.

Is there are problem with that? Does this create multiple objects or does it destroy the existing DirectoryInfo object and create a new one?

Here is the relevant source:


ArrayList alFiles = new ArrayList();
ArrayList alFolders = new ArrayList();
FileInfo[] files;

alFolders.Add(rootPath);
while(alFolders.Count > 0)
{
DirectoryInfo currentFolder = new DirectoryInfo(alFolders[0].ToString());
folders = currentFolder.GetDirectories();
foreach(DirectoryInfo subFolder in folders)
alFolders.Add(currentFolder.FullName + "\\" + subFolder.Name);

files = currentFolder.GetFiles();
foreach(FileInfo file in files)
{
if (file.Name.EndsWith("xml"))
alFiles.Add(file.Name);
}

alFolders.RemoveAt(0);
}
 
P

Peter Rilling

I do not see a problem with that. The old objects will be destroyed when
garbage collection happens (as long as no other references exist, which it
looks like there is not).

As a side not, you might get cleaner code using a Queue object (not that
anything is wrong with your code, just an observation), that way you can
just Enqueue and Dequeue your items.

I am recursing through ALL folders and sub-folders below a certain level to
list all the files of a certain type in those folders. I use two
ArrayLists, alFiles and alFolders, to track matching files and my progress
in the recursion.

I use a while loop to manage the folder-subfolder drill-down. Each pass
through the while loop creates a new DirectoryInfo object named
currentFolder.

Is there are problem with that? Does this create multiple objects or does
it destroy the existing DirectoryInfo object and create a new one?

Here is the relevant source:


ArrayList alFiles = new ArrayList();
ArrayList alFolders = new ArrayList();
FileInfo[] files;

alFolders.Add(rootPath);
while(alFolders.Count > 0)
{
DirectoryInfo currentFolder = new DirectoryInfo(alFolders[0].ToString());
folders = currentFolder.GetDirectories();
foreach(DirectoryInfo subFolder in folders)
alFolders.Add(currentFolder.FullName + "\\" + subFolder.Name);

files = currentFolder.GetFiles();
foreach(FileInfo file in files)
{
if (file.Name.EndsWith("xml"))
alFiles.Add(file.Name);
}

alFolders.RemoveAt(0);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top