How do I get number of Files from a folder using ASP.NET with 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())
System.IO.Directory myDir = GetMyDirectoryForTheExample();
int count = myDir.GetFiles().Length;
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
.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.