Groups | Blog | Home
all groups > dotnet framework > may 2006 >

dotnet framework : Nested iterator problem



Tasos Vogiatzoglou
5/21/2006 5:53:45 AM
This works for me ...

class Program
{
private static string dirF = @"a dir with files";

public static void Main(string[] args)
{
foreach (FileInfo info in Files)
{
Console.WriteLine(info.FullName);
}

Console.ReadLine();
}

public static IEnumerable<FileInfo> Files
{
get
{
foreach (DirectoryInfo dir in SubDirectories(new
DirectoryInfo(dirF)))
{
foreach (FileInfo fileInfo in dir.GetFiles())
{
yield return fileInfo;
}
}
}
}

static IEnumerable<DirectoryInfo> SubDirectories(DirectoryInfo
di)
{
yield return di;
foreach (DirectoryInfo directory in di.GetDirectories())
{
foreach (DirectoryInfo subDirectory in
SubDirectories(directory))
{
yield return subDirectory;
}
}
}
}

regards,
Tasos
Carl Daniel [VC++ MVP]
5/21/2006 7:09:36 AM
[quoted text, click to view]

This means that you're building with DEBUG not defined. Check your project
settings. Were you debugging a Release build by chance?

If you're looking for recursive file enumeration in particular, you might
like:

http://www.codeproject.com/csharp/FileSystemEnumerator.asp

Of course, if this is just an exercise in using the new iterator support,
then carry on - you're on the right track!

-cd

Andrew Matthews
5/21/2006 11:14:48 AM
Hi All,

I have an issue that I can't solve with the following (cleaned up) piece
of code. What I've seen in the VS 2005 debugger is that the Files iterator
is issuing a yield on all of the files below 'dir', but that the loop in
main does nothing with them. i.e. if there were 10 files below dir, then
it would stop at the 'FileInfo info' 10 times, but would never visit the
Debug.WriteLine 10 times. I can't see what I am doing wrong here (if anything).

I know that under the hood there is a fair bit of code transformation required
to execute the iterators, so I wonder whether using an iterator from within
another iterator causes problems?

I also have the LINQ (May 2006 CTP) installed as well. Is there a chance
that this is causing a problem?

TIA

Andrew Matthews
=================================================
public class MyClass
{
private string dir = @"c:\somedir\someotherdir";

public static void main(string[] args)
{
foreach (FileInfo info in Files)
{
Debug.WriteLine(info.FullName);
}
}

public IEnumerable<FileInfo> Files
{
get
{
foreach (DirectoryInfo dir in SubDirectories(new DirectoryInfo(dir)))
{
foreach (FileInfo fileInfo in dir.GetFiles())
{
yield return fileInfo;
}
}
}
}

IEnumerable<DirectoryInfo> SubDirectories(DirectoryInfo di)
{
yield return di;
foreach (DirectoryInfo directory in di.GetDirectories())
{
foreach (DirectoryInfo subDirectory in SubDirectories(directory))
{
yield return subDirectory;
}
}
}


AddThis Social Bookmark Button