Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder
Go Back  Xtreme Visual Basic Talk > > > Reading All Files In 'Windows' Folder


Reply
 
Thread Tools Display Modes
  #1  
Old 08-23-2011, 07:02 PM
jackdawkc jackdawkc is offline
Newcomer
 
Join Date: Aug 2010
Posts: 1
Default Reading All Files In 'Windows' Folder


Hello
I'm trying to return a integer / count of the ammount of files in the directory and sub directories in the 'Windows' folder, I need to be able to do this as fast as possible (no lag) and tell when it's done, hope I explained this right. Any help would be appriceated

(.NET Framework 2.0)
Reply With Quote
  #2  
Old 08-26-2011, 05:59 AM
NFITC1 NFITC1 is offline
Centurion
 
Join Date: Apr 2006
Posts: 102
Default

I think there's a class in the My.Computer.FileSystem package called DirInfo that can tell you how many files are in the dir. I used it to create a little prog to tell me where my drive's space was being used.
Reply With Quote
  #3  
Old 08-26-2011, 08:10 AM
Roger_Wgnr's Avatar
Roger_Wgnr Roger_Wgnr is offline
CodeASaurus Hex

Forum Leader
* Expert *
 
Join Date: Jul 2006
Location: San Antonio TX
Posts: 2,427
Default

Since you specified .NET 2.0 you have to do a bit more to get the count.
.NET 2.0 does not have the Windows Special Folder defined so you have to get the parent path to the System folder.

This is untested and may need a bit of adjustment as I did not use VS.
Code:
        Dim dirCount As Integer
        Dim WinDirPath As String = FileSystem.GetParentPath(Environment.GetFolderPath(Environment.SpecialFolder.System))
        Dim FileList As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
        FileList = FileSystem.GetFiles(WinDirPath, SearchOption.SearchAllSubDirectories, "*.*")
        dirCount = FileList.Count
__________________
Code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. ~Martin Golding
The user is a peripheral that types when you issue a read request. ~Peter Williams
MSDN Visual Basic .NET General FAQ
Reply With Quote
  #4  
Old 08-26-2011, 09:22 AM
AtmaWeapon's Avatar
AtmaWeaponReading All Files In 'Windows' Folder AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Here's a method I like better, though it does the same thing and has the same caveats. The "no lag" part's going to take some work.
Code:
Dim windowsPath As String = Environment.GetEnvironmentVariable("windir")
Dim files() As String = System.IO.Directory.GetFiles(windowsPath, "*.*", SearchOption.AllDirectories)
Dim length = files.Length
Here's why I like it better:
  • I don't like doing path algebra, and don't know if System is guaranteed to be in the Windows directory. (To be fair, I don't know if %windir% is guaranteed either.)
  • Microsoft.VisualBasic.IO.FileSystem is there to make VB6 application ports work easier; .NET developers rarely reach for anything under Microsoft.VisualBasic.*.
  • True to its awkward form, FileSystem.GetFiles() returns ReadOnlyCollection(Of String) instead of a simple array. The contract perspective is nice, but from a usability perspective it stinks.
The trouble is in either case GetFiles() is based on the API methods FindFirstFile() and FindNextFile(). The short version of the story: it has to read all files before it can return, so if you just plop this in a button click event your form's going to sit unresponsive until it finishes. To solve this, you need to use a worker thread. The easiest way to do this is the BackgroundWorker class. Add this class to your project, then follow the instructions:
Code:
Public Class CountFilesWorker
    Inherits BackgroundWorker

    Protected Overrides Sub OnDoWork(ByVal e As DoWorkEventArgs)
        Dim windowsPath As String = Environment.GetEnvironmentVariable("windir")
        Dim files() As String = System.IO.Directory.GetFiles(windowsPath, "*.*", SearchOption.AllDirectories)
        Dim length = files.Length
        e.Result = length
    End Sub
End Class
You can read about how BackgroundWorker works if you're curious.

Anyway, once you've added that file to your class:
  • Handle the worker's RunWorkerCompleted event; that's where you update your UI with the count.
  • Call the worker's RunWorkerAsync() method: that's what starts counting.
Here's a primitive example that assumes some controls on your form:
Code:
Public Class YourForm
    
    Private _worker As CountFilesWorker

    Sub Button1_Click(...)
        _worker = New CountFilesWorker()
        AddHandler _worker.RunWorkerCompleted, AddressOf WorkerFinishedCounting
        _worker.RunWorkerAsync()
    End Sub

    Sub WorkerFinishedCounting(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs)
        If e.Error IsNot Nothing Then
            MessageBox.Show("An error occurred: " & e.Message)
        Else
            Dim fileCount As Integer = CInt(e.Result)
            MessageBox.Show("There were " & fileCount & " files.")
        End If

        RemoveHandler _worker, AddressOf WorkerFinishedCounting
    End Sub

End Class
When you call RunWorkerAsync(), the worker starts a thread. It calls its own OnDoWork() method on that thread. That's where my code counts the files. It's important to know you cannot update controls from this method because it is unsafe to make cross-thread calls. When OnDoWork() is finished, the background worker takes the e.Result property and creates a RunWorkerCompletedEventArgs that holds it. That's passed along when the RunWorkerCompleted event is raised on the main thread. This is handled by WorkerFinishedCounting, which pulls out the count and displays it. If OnDoWork() throws an exception, the background worker catches it and puts it in the e.Error property you can access from the RunWorkerCompleted handler.

Since this counts the files on a worker thread, the main thread won't get laggy. You may want to display a "Counting..." indicator to show the user the application's actually counting the files.

If you were using a more modern version of .NET (2.0 is 6 years old and 3 versions behind!) you could get the Windows directory more reliably and use the Directory.EnumerateFiles() API to make it easier to do neat things like provide a sort-of accurate progress indicator. It'd still have to take place on a worker thread though.

Super-advanced programmers may note there are some low-level filesystem API calls that can get file counts much faster. It takes some serious voodoo to use these from .NET and I bet it'd take 300 or so lines of infrastructure. I'm not going down that road, though it interests me.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
Reply

Tags
.net 2.0, directory, file i/o, read


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder
 
Reading All Files In 'Windows' Folder
Reading All Files In 'Windows' Folder
 
-->