
Grabbing 1st file in a directory
Quote:
>> Okay, now that I think about it, I guess that's right. Shows how long it's
>> been since I've used Dir().... Regardless of the bad example, the jist of
>> what Tom and I are saying holds true: If you must hate .NET, hate it for
> the
>> right reasons, not for whiny stuff.
> Whiny stuff? Eight years on with their masterpiece,
> 200+ MB of support files, and anyone who wants to
> enumerate files needs to "wait for the next version"?
You can enumerate files now.
For Each file As FileInfo in Directory.GetFiles(myDirPath)
' do stuff
Next
or if you must:
Dim p As String = Dir("C:\")
While p <> ""
Console.WriteLine(p)
p = Dir()
End While
The question came up, because the current implementation does a complete
enumeration before returning. This is not usually a problem, unless your
dealing with a lot of files - but can be wasteful if all you care about is the
first file or don't plan to process all of the files.
They are adding some methods in V4 that return an IEnumerable<T> interface so
that you can enumerate in a streaming manner - a pattern that is becomming
much more common in the framework. Though it's trivial to write a
replacement right now (even in VB.NET - though, it's even easier in C#).
Quote:
> That's comedy, not whiny. And Tom added to the
> comedy without knowing it by explaining that one
> need only write a C# library to handle the job. Like
> I said, you couldn't make this stuff up. :)
I suggested C# simply because it makes it slightly simpler to write the
enumerator. It could be done in VB.NET, it just takes a bit more code.
public static IEnumerable<DirectoryInfo> EnumerateDirectories ( this DirectoryInfo target )
{
string searchPath = Path.Combine ( target.FullName, "*" );
NativeWin32.WIN32_FIND_DATA findData;
using (NativeWin32.SafeSearchHandle hFindFile = NativeWin32.FindFirstFile ( searchPath, out findData ))
{
do
{
if ( (findData.dwFileAttributes & FileAttributes.Directory) != 0 && findData.cFileName != "." && findData.cFileName != ".." )
{
yield return new DirectoryInfo ( Path.Combine ( target.FullName, findData.cFileName ) );
}
} while ( NativeWin32.FindNextFile ( hFindFile, out findData ) );
}
Quote:
}
I've obviously left out the api call declarations, but usage of the above
would look like:
DirectoryInfo root = new DirectoryInfo ( "C:\\" );
Console.WriteLine ( root.FullName );
foreach ( DirectoryInfo subDir in root.EnumerateDirectories () )
{
Console.WriteLine ( "\t{0}", subDir.Name );
Quote:
}
> Actually, though, that all does seem to connect to
> one of the "right reasons" to criticize .Net. It's
> not so strong on basic shell/desktop functionality
> because it was never intended to be. Which is fine
> ...if only MS didn't insist on telling people otherwise.
Which is again, rooted in your complete misunderstanding of .NET.
--
Tom Shelton