C# 文件夹中的文件数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2242564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:41:13  来源:igfitidea点击:

File count from a folder

c#asp.net

提问by Sreejesh Kumar

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

如何使用 ASP.NET 和 C# 从文件夹中获取文件数?

采纳答案by X4lldux

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

回答by rahul

You can use the Directory.GetFilesmethod

您可以使用Directory.GetFiles方法

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

另请参阅Directory.GetFiles 方法(字符串、字符串、搜索选项)

You can specify the search option in this overload.

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

TopDirectoryOnly: Includes only the current directory in a search.

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

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.

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;

回答by Dean

The slickest method woud be to use LINQ:

最巧妙的方法是使用LINQ

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

回答by Krishna Thota

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

You can use this.

你可以用这个。

回答by Nalan Madheswaran

Reading PDF files from a directory:

从目录中读取 PDF 文件:

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

}

回答by Wessam El Mahdy

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

要使用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 anagha

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;


回答by detale

.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.

.NET 方法 Directory.GetFiles(dir) 或 DirectoryInfo.GetFiles() 仅用于获取文件总数并不是很快。如果你非常频繁地使用这种文件计数方法,可以考虑直接使用 WinAPI,这样可以节省大约 50% 的时间。

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

这是我将 WinAPI 调用封装到 C# 方法的 WinAPI 方法:

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

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

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

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

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

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.

注意:第一次运行任何一种方法都会分别慢 60% - 100%,因为硬盘驱动器需要更长的时间来定位扇区。我猜后续调用将被 Windows 半缓存。

回答by Josue Martinez

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

回答by Varun

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