文件夹中的文件计数


80

如何使用带有C#的ASP.NET从文件夹中获取文件数量?

Answers:


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

3
如果目录包含多个int.MaxValue文件,该怎么办?
梅尔·吉拉特斯

2
要获得更节省资源的最新解决方案,请用EnumerateFiles()代替GetFiles()并用Count()代替Length
relative_random

128

您可以使用Directory.GetFiles方法

另请参见Directory.GetFiles方法(字符串,字符串,SearchOption)

您可以在此重载中指定搜索选项。

TopDirectoryOnly:搜索中仅包含当前目录。

AllDirectories:在搜索操作中包括当前目录和所有子目录。此选项包括重新解析点,例如搜索中的安装驱动器和符号链接。

// 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;

我可以建议使用“ *”来匹配文件,否则不带扩展名的文件将不包括在内。
尼克·布尔

这似乎包括子文件夹的数量。也就是说,我有一个子文件夹,在人少的目录,这将返回1
善待新用户

@MichaelPotter是否有可能正在计算desktop.ini?
Heriberto Lugo

要获得更节省资源的最新解决方案,请用EnumerateFiles()代替GetFiles()并用Count()代替Length
relative_random

21

最好的方法是使用LINQ

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

5
您可以编写:var fileCount = Directory.EnumerateFiles(@“ H:\ iPod_Control \ Music”,“ * .mp3”,SearchOption.AllDirectories).Count();
AndrewS

1
在大量文件收集的情况下,我建议使用此方法。这种方法可以节省内存。方法GetFilecreate string []需要平面存储空间。注意:)
hsd


8

从目录读取PDF文件:

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

}

不必要地定义列表。这应该可以完成工作:if Directory.Getfiles(@“ C:\ ScanPDF”,“ * .pdf”)。count> 0
Stefan Meyer

@StefanMeyer不,如果您以后再使用该列表...
Guille Bauza,

@GuilleBauza问题是要统计PDF文件,而不是使用它们;)
Stefan Meyer

是的,但是如果您不使用它,那么计数的意义是什么……
Guille Bauza

3

.NET方法Directory.GetFiles(dir)或DirectoryInfo.GetFiles()对于仅获取总文件数而言不是很快。如果您大量使用此文件计数方法,请考虑直接使用WinAPI,这样可以节省大约50%的时间。

这是WinAPI方法,其中封装了对C#方法的WinAPI调用:

int GetFileCount(string dir, bool includeSubdirectories = false)

完整的代码:

[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;
}

当我在计算机上搜索包含13000个文件的文件夹时-平均:110ms

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

.NET内置方法:Directory.GetFiles(dir)-平均:230ms

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

注意:这两种方法的首次运行速度将分别降低60%-100%,因为硬盘驱动器需要更长的时间来定位扇区。我猜以后的调用将被Windows半缓存。


很好,但要使其正常工作,我建议进行以下编辑:||||||||||||||添加公共静态long fileCount = 0; ||||||||||||| // int fileCount = 0; //评论
Markus

3
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

2

尝试使用以下代码来获取文件夹中文件的数量

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



-1

要使用LINQ获得某些类型扩展的数量,可以使用以下简单代码:

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())
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.