File count from a folder

C#asp.net

C# Problem Overview


How do I get number of Files from a folder using ASP.NET with C#?

C# Solutions


Solution 1 - C#

You can use the Directory.GetFiles method

Also see Directory.GetFiles Method (String, String, SearchOption)

You can specify the search option in this overload.

TopDirectoryOnly: Includes only the current directory in a search.

AllDirectories: Includes the current directory and all the subdirectories in a search operation. This option includes reparse points like mounted drives and symbolic links in the search.

// searches the current directory and sub directory
int fCount = Directory.GetFiles(path, "*", SearchOption.AllDirectories).Length;
// searches the current directory
int fCount = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly).Length;

Solution 2 - C#

System.IO.Directory myDir = GetMyDirectoryForTheExample();
int count = myDir.GetFiles().Length;

Solution 3 - C#

The slickest method woud be to use LINQ:

var fileCount = (from file in Directory.EnumerateFiles(@"H:\iPod_Control\Music", "*.mp3", SearchOption.AllDirectories)
                        select file).Count();

Solution 4 - C#

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("SourcePath");
int count = dir.GetFiles().Length;

You can use this.

Solution 5 - C#

Reading PDF files from a directory:

var list = Directory.GetFiles(@"C:\ScanPDF", "*.pdf");
if (list.Length > 0)
{

}

Solution 6 - C#

.NET methods Directory.GetFiles(dir) or DirectoryInfo.GetFiles() are not very fast for just getting a total file count. If you use this file count method very heavily, consider using WinAPI directly, which saves about 50% of time.

Here's the WinAPI approach where I encapsulate WinAPI calls to a C# method:

int GetFileCount(string dir, bool includeSubdirectories = false)

Complete code:

[Serializable, StructLayout(LayoutKind.Sequential)]
private struct WIN32_FIND_DATA
{
    public int dwFileAttributes;
    public int ftCreationTime_dwLowDateTime;
    public int ftCreationTime_dwHighDateTime;
    public int ftLastAccessTime_dwLowDateTime;
    public int ftLastAccessTime_dwHighDateTime;
    public int ftLastWriteTime_dwLowDateTime;
    public int ftLastWriteTime_dwHighDateTime;
    public int nFileSizeHigh;
    public int nFileSizeLow;
    public int dwReserved0;
    public int dwReserved1;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
    public string cFileName;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
    public string cAlternateFileName;
}

[DllImport("kernel32.dll")]
private static extern IntPtr FindFirstFile(string pFileName, ref WIN32_FIND_DATA pFindFileData);
[DllImport("kernel32.dll")]
private static extern bool FindNextFile(IntPtr hFindFile, ref WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll")]
private static extern bool FindClose(IntPtr hFindFile);

private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
private const int FILE_ATTRIBUTE_DIRECTORY = 16;

private int GetFileCount(string dir, bool includeSubdirectories = false)
{
    string searchPattern = Path.Combine(dir, "*");

    var findFileData = new WIN32_FIND_DATA();
    IntPtr hFindFile = FindFirstFile(searchPattern, ref findFileData);
    if (hFindFile == INVALID_HANDLE_VALUE)
        throw new Exception("Directory not found: " + dir);

    int fileCount = 0;
    do
    {
        if (findFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
        {
            fileCount++;
            continue;
        }

        if (includeSubdirectories && findFileData.cFileName != "." && findFileData.cFileName != "..")
        {
            string subDir = Path.Combine(dir, findFileData.cFileName);
            fileCount += GetFileCount(subDir, true);
        }
    }
    while (FindNextFile(hFindFile, ref findFileData));

    FindClose(hFindFile);

    return fileCount;
}

When I search in a folder with 13000 files on my computer - Average: 110ms

int fileCount = GetFileCount(searchDir, true); // using WinAPI

.NET built-in method: Directory.GetFiles(dir) - Average: 230ms

int fileCount = Directory.GetFiles(searchDir, "*", SearchOption.AllDirectories).Length;

Note: first run of either of the methods will be 60% - 100% slower respectively because the hard drive takes a little longer to locate the sectors. Subsequent calls will be semi-cached by Windows, I guess.

Solution 7 - C#

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; // Will Retrieve count of all files in directry and sub directries

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length; // Will Retrieve count of all files in directry but not sub directries

int fileCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length; // Will Retrieve count of files XML extension in directry and sub directries

Solution 8 - C#

int filesCount = Directory.EnumerateFiles(Directory).Count();

Solution 9 - C#

Try following code to get count of files in the folder

string strDocPath = Server.MapPath('Enter your path here'); 
int docCount = Directory.GetFiles(strDocPath, "*", 
SearchOption.TopDirectoryOnly).Length;

Solution 10 - C#

The System.IO namespace provides such a facility. It contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support.

For example, if you wanted to count the number of files in the C:\ directory, you would say (Note that we had to escape the '\' character with another '\'):

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("C:\\");
int count = dir.GetFiles().Length;

You could also escape the '\' character by using the verbatim string literal whereby anything in the string that would normally be interpreted as an escape sequence is ignored, i.e. instead of ("C:\\"), you could say, (@"C:\")

Solution 11 - C#

To get the count of certain type extensions using LINQ you could use this simple code:

Dim exts() As String = {".docx", ".ppt", ".pdf"}

Dim query = (From f As FileInfo In directory.GetFiles()).Where(Function(f) exts.Contains(f.Extension.ToLower()))

Response.Write(query.Count())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSreejesh KumarView Question on Stackoverflow
Solution 1 - C#rahulView Answer on Stackoverflow
Solution 2 - C#X4llduxView Answer on Stackoverflow
Solution 3 - C#DeanView Answer on Stackoverflow
Solution 4 - C#Krishna ThotaView Answer on Stackoverflow
Solution 5 - C#Nalan MadheswaranView Answer on Stackoverflow
Solution 6 - C#detaleView Answer on Stackoverflow
Solution 7 - C#VarunView Answer on Stackoverflow
Solution 8 - C#Josue MartinezView Answer on Stackoverflow
Solution 9 - C#anaghaView Answer on Stackoverflow
Solution 10 - C#Dean PView Answer on Stackoverflow
Solution 11 - C#Wessam El MahdyView Answer on Stackoverflow