peterchen
peterchen

Reputation: 41106

Windows / NTFS: Number of files in a directory, without enumerating them

Is there a way in Windows to get the number of files in a directory (non-recursively is good enough) without the potentially significant overhead of enumerating them all through FindFirst/NextFile?

The purpose is for an estimate how many files need to be processed.
The directory structure is known and not deep, and folders usually don't contain unknown files.

Since the data is not essential to continue and the folder is virtually always on a local drive, an NTFS-specific command would be acceptable (provided that does not require elevation).

Any ideas?

Upvotes: 1

Views: 445

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308206

Keeping track of the number of files in a directory is an overhead that doesn't provide any benefit for a file system, so none of them do it.

Counting files on a local drive should be fast enough for most purposes. It will certainly take a small fraction of the time needed to process the files.

Upvotes: 2

athoik
athoik

Reputation: 363

Assuming that Indexing service is running and the directory is indexed, we can query the catalog and count the files on a given directory.

I dont know if querying the catalog is faster, its the only idea came on my mind.

Regards.

Sample code in VB.NET

Sub Main()

    Try
        ' Catalog Name
        Dim strCatalog As String = "System"

        Dim strQuery As String
        strQuery = "Select DocPageCount,DocTitle,Filename,Size,PATH,URL from SCOPE('shallow traversal of ""C:\Windows""')"

        Dim connString As String = "Provider=MSIDXS.1;Integrated Security .='';Data Source='" & strCatalog & "'"

        Dim cn As New System.Data.OleDb.OleDbConnection(connString)
        cn.Open()

        Dim cmd As New System.Data.OleDb.OleDbCommand(strQuery, cn)
        Dim rdr As System.Data.OleDb.OleDbDataReader = cmd.ExecuteReader()

        Dim files As Integer = 0

        While rdr.Read()
            files += 1
            Console.WriteLine("Path: {0} Filename: {1} Size : {2}", rdr("PATH"), rdr("Filename"), rdr("Size"))
        End While

        rdr.Close()
        rdr = Nothing
        cmd.Dispose()
        cmd = Nothing

        cn.Close()

        Console.WriteLine("Total Files: {0}", files)

    Catch ex As Exception
        Console.WriteLine(ex)
    End Try
End Sub

More info: Searching your web site with the Microsoft Indexing Service and ASP.NET

Upvotes: 1

Related Questions