Làm cách nào để lấy số Tệp từ một thư mục bằng ASP.NET với C #?
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:
System.IO.Directory myDir = GetMyDirectoryForTheExample();
int count = myDir.GetFiles().Length;
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;
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();
GetFiletạo chuỗi [] yêu cầu không gian bộ nhớ phẳng. Hãy cẩn thận :)
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.
Đọc tệp PDF từ một thư mục:
var list = Directory.GetFiles(@"C:\ScanPDF", "*.pdf");
if (list.Length > 0)
{
}
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.
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
int filesCount = Directory.EnumerateFiles(Directory).Count();
Để 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())