Số lượng tệp từ một thư mục


80

Làm cách nào để lấy số Tệp từ một thư mục bằng ASP.NET với C #?

Câu trả lời:


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

3
Hành vi là gì nếu thư mục chứa nhiều hơn các tệp int.MaxValue?
— Mel Gerats

2
Để có giải pháp cập nhật hơn, nhẹ hơn về tài nguyên, hãy thay thế GetFiles () bằng EnumerateFiles () và Length by Count ()
— tương

128

Bạn có thể sử dụng phương thức Directory.GetFiles

Cũng xem Phương pháp Directory.GetFiles (Chuỗi, Chuỗi, Tìm kiếm)

Bạn có thể chỉ định tùy chọn tìm kiếm trong phần quá tải này.

TopDirectoryOnly : Chỉ bao gồm thư mục hiện tại trong một tìm kiếm.

AllDirectories : Bao gồm thư mục hiện tại và tất cả các thư mục con trong thao tác tìm kiếm. Tùy chọn này bao gồm các điểm tổng hợp lại như ổ đĩa được gắn và các liên kết tượng trưng trong tìm kiếm.

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

Tôi có thể đề xuất sử dụng "*" để đối sánh các tệp, nếu không, các tệp không có phần mở rộng sẽ không được tính vào số lượng.
— Nick Bull

Điều này dường như bao gồm số lượng các thư mục con. Đó là, tôi có một thư mục con và trong một thư mục khác rỗng và lợi nhuận này 1.
— Be Kind Users Để Mới

@MichaelPotter có khả năng nó đang đếm desktop.ini không?
— Heriberto Lugo

Để có giải pháp cập nhật hơn, nhẹ hơn về tài nguyên, hãy thay thế GetFiles () bằng EnumerateFiles () và Length by Count ()
— tương

21

Phương pháp khéo léo nhất sẽ được sử dụng LINQ :

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

5
Bạn chỉ có thể viết: var fileCount = Directory.EnumerateFiles (@ "H: \ iPod_Control \ Music", "* .mp3", SearchOption.AllDirectories) .Count ();
— AndrewS

1
Tôi đã đề xuất phương pháp này trong trường hợp có bộ sưu tập tệp lớn. Cách tiếp cận này giúp tiết kiệm bộ nhớ. Phương thức GetFiletạo chuỗi [] yêu cầu không gian bộ nhớ phẳng. Hãy cẩn thận :)
— hsd

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

Bạn có thể sử dụng cái này.


8

Đọc tệp PDF từ một thư mục:

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

}

Định nghĩa khác thường về một danh sách. Điều này sẽ thực hiện công việc: if Directory.Getfiles (@ "C: \ ScanPDF", "* .pdf"). Count> 0
— Stefan Meyer

@StefanMeyer Không nếu bạn sẽ sử dụng danh sách mà sau này ...
— Guille Bauza

@GuilleBauza Câu hỏi đặt ra là để đếm các tập tin PDF, không sử dụng chúng;)
— Stefan Meyer

Có, nhưng quan điểm đếm những gì nếu bạn sẽ không sử dụng nó ...
— Guille Bauza

3

Các phương thức .NET Directory.GetFiles (dir) hoặc DirectoryInfo.GetFiles () không nhanh lắm để chỉ nhận được tổng số tệp. Nếu bạn sử dụng phương pháp đếm tệp này rất nhiều, hãy xem xét sử dụng WinAPI trực tiếp , điều này giúp tiết kiệm khoảng 50% thời gian.

Đây là cách tiếp cận WinAPI mà tôi đóng gói các lệnh gọi WinAPI vào một phương thức C #:

int GetFileCount(string dir, bool includeSubdirectories = false)

Hoàn thành mã:

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

Khi tôi tìm kiếm trong một thư mục có 13000 tệp trên máy tính của mình - Trung bình: 110ms

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

Phương thức tích hợp .NET: Directory.GetFiles (dir) - Trung bình: 230ms

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

Lưu ý: lần chạy đầu tiên của một trong hai phương pháp sẽ chậm hơn tương ứng 60% - 100% vì ổ cứng mất nhiều thời gian hơn để định vị các cung. Tôi đoán là các cuộc gọi tiếp theo sẽ được Windows bán vào bộ nhớ đệm.


Tuyệt vời nhưng để nó hoạt động, tôi khuyên bạn nên chỉnh sửa sau: |||||||||||| thêm public static long fileCount = 0; ||||||||||||| // int fileCount = 0; // bình luận
— 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

Hãy thử mã sau để có được số lượng tệp trong thư mục

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



-1

Để có được số lượng tiện ích mở rộng loại nhất định bằng LINQ, bạn có thể sử dụng mã đơn giản sau:

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())
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookie và Chính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.