Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 文件夹中的文件计数_C#_Asp.net - Fatal编程技术网

C# 文件夹中的文件计数

C# 文件夹中的文件计数,c#,asp.net,C#,Asp.net,如何使用ASP.NET和C#?从文件夹中获取文件数您可以使用方法 另请参见 您可以在此重载中指定搜索选项 TopDirectoryOnly:在搜索中仅包括当前目录 所有目录:包括搜索操作中的当前目录和所有子目录。此选项包括重新分析点,如搜索中已安装的驱动器和符号链接 // searches the current directory and sub directory int fCount = Directory.GetFiles(path, "*", SearchOption.AllDirec

如何使用ASP.NET和C#?

从文件夹中获取文件数您可以使用方法

另请参见

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

TopDirectoryOnly:在搜索中仅包括当前目录

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

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

最巧妙的方法是使用:


您可以使用它。

从目录中读取PDF文件:

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

}

要使用获取特定类型扩展的计数,可以使用以下简单代码:

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())

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

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

NET方法Directory.GetFiles(dir)或DirectoryInfo.GetFiles()仅获取文件总数并不是很快。 如果你使用这个文件计数方法非常严重,考虑<强>使用WiNAPI直接< /强>,它节省了大约50%的时间。 下面是我将WinAPI调用封装到C#方法的WinAPI方法:

完整代码:

[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
int fileCount = Directory.GetFiles(searchDir, "*", SearchOption.AllDirectories).Length;
.NET内置方法:Directory.GetFiles(dir)-平均值:230ms

int fileCount = GetFileCount(searchDir, true); // using WinAPI
int fileCount = Directory.GetFiles(searchDir, "*", SearchOption.AllDirectories).Length;

注意:这两种方法的第一次运行速度将分别降低60%-100%,因为硬盘驱动器定位扇区所需的时间稍长。我想后续调用将由Windows半缓存。

System.IO命名空间提供了这样一种功能。它包含允许读写文件和数据流的类型,以及提供基本文件和目录支持的类型

int filesCount = Directory.EnumerateFiles(Directory).Count();
例如,如果您想计算
C:\
目录中的文件数,您会说(注意,我们必须用另一个'\'转义'\'字符):


您还可以通过使用逐字字符串文字来转义“\”字符,从而忽略字符串中通常被解释为转义序列的任何内容,即,您可以说,
(@“C:\”)
,而不是
(@“C:\”)

我建议使用“*”来匹配文件,否则,没有扩展名的文件将不包括在计数中。这似乎包括子文件夹的计数。也就是说,我有一个子文件夹,在一个空目录中,这返回1。@MichaelPotter有可能是在计算desktop.ini吗?要获得一个资源更轻松的最新解决方案,请将GetFiles()替换为EnumerateFiles(),将Length替换为Count(),您只需编写:var fileCount=directory.EnumerateFiles(@“H:\iPod\U Control\Music”,“*.mp3”,SearchOption.AllDirectories.Count();我建议在收集大量文件时使用这种方法。这种方法可以节省内存。方法
GetFile
创建字符串[],该字符串需要平坦的内存空间。小心:)如果目录包含的文件超过int.MaxValue,会发生什么情况?要获得更为先进的解决方案,更省力的资源,请使用EnumerateFiles()替换GetFiles(),使用Count替换Length(),这是一个很好的解决方案,但要使其正常工作,我建议进行以下编辑:| ||||||||添加公共静态长文件计数=0;||||||||||//int fileCount=0//注释掉不必要的列表定义。这应该可以完成以下工作:if Directory.Getfiles(@“C:\ScanPDF”,“*.pdf”).count>0@StefanMeyer不,如果你以后要使用该列表…@GuilleBauza问题是要计算PDF文件,而不是使用它们;)是的,但是如果你不使用它,计数又有什么意义呢…@GuilleBauza很多场景。例如,决定使用文件夹做什么,但不关心文件。这只是一个不同的场景。
int fileCount = Directory.GetFiles(searchDir, "*", SearchOption.AllDirectories).Length;
int filesCount = Directory.EnumerateFiles(Directory).Count();
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
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("C:\\");
int count = dir.GetFiles().Length;