如何使用带C#的ASP.NET从文件夹中获取文件数?
答案 0 :(得分:110)
您可以使用 Directory.GetFiles 方法
另见 Directory.GetFiles Method (String, String, 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 :(得分:42)
System.IO.Directory myDir = GetMyDirectoryForTheExample();
int count = myDir.GetFiles().Length;
答案 2 :(得分:21)
最简单的方法是使用LINQ:
var fileCount = (from file in Directory.EnumerateFiles(@"H:\iPod_Control\Music", "*.mp3", SearchOption.AllDirectories)
select file).Count();
答案 3 :(得分:11)
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("SourcePath");
int count = dir.GetFiles().Length;
你可以使用它。
答案 4 :(得分:6)
从目录中读取PDF文件:
var list = Directory.GetFiles(@"C:\ScanPDF", "*.pdf");
if (list.Length > 0)
{
}
答案 5 :(得分:1)
尝试使用以下代码来获取文件夹中的文件数
string strDocPath = Server.MapPath('Enter your path here');
int docCount = Directory.GetFiles(strDocPath, "*",
SearchOption.TopDirectoryOnly).Length;
答案 6 :(得分:1)
.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进行半缓存。
答案 7 :(得分:0)
int filesCount = Directory.EnumerateFiles(Directory).Count();
答案 8 :(得分:0)
code.test.js
答案 9 :(得分:0)
System.IO 命名空间提供了这样的功能。它包含允许读写文件和数据流的类型,以及提供基本文件和目录支持的类型。
例如,如果您想计算
class maskrcnn_Dataset(torch.utils.data.Dataset):
def __init__(self, root, transforms=None):
self.root = root
self.transforms = transforms
# load all image files, sorting them to
# ensure that they are aligned
self.imgs = list(sorted(os.listdir(os.path.join(root, "images"))))
self.masks = list(sorted(os.listdir(os.path.join(root, "masks"))))
#self.class_masks = list(sorted(os.listdir(os.path.join(root, "SegmentationClass"))))
def __getitem__(self, idx):
# load images ad masks
img_path = os.path.join(self.root, "images", self.imgs[idx])
x=self.imgs[idx].split('.')
mask_path = os.path.join(self.root, "masks", self.masks[idx])
#class_mask_path = os.path.join(self.root, "SegmentationClass", self.class_masks[idx])
#read and convert image to RGB
img = cv2.imread(img_path)
mask_for_all=[]
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# note that we haven't converted the mask to RGB,
# because each color corresponds to a different instance
# with 0 being background
# mask = Image.open(mask_path)
mask_folder=os.path.join(self.root,"masks")
source_mask = os.path.join(mask_folder, x[0])
#print(os.listdir(source_mask))
boxes = []
xx=trier(os.listdir(source_mask))
#print(xx)
for file_name in xx:
mask = Image.open(os.path.join(source_mask,file_name))
mask = np.array(mask)
mask_for_all.append(mask)
obj_ids = np.unique(mask)
obj_ids = obj_ids[1:]
masks = mask == obj_ids[:, None, None]
num_objs = len(obj_ids)
for i in range(num_objs):
pos = np.where(masks[i])
xmin = np.min(pos[1])
xmax = np.max(pos[1])
ymin = np.min(pos[0])
ymax = np.max(pos[0])
boxes.append([xmin, ymin, xmax, ymax])
num_objs=len(boxes)
boxes = torch.as_tensor(boxes, dtype=torch.float32)
# there is only one class
if(self.root.find("train")!=-1):
#print("bisgltjf")
labels =class_ids_train[class_ids_train_names.index(self.imgs[idx])]
#print(labels)
else:
labels =class_ids_val[class_ids_val_names.index(self.imgs[idx])]
#print('l3assba')
#labels = np.array([])
#for i in range(masks.shape[0]):
# labels = np.append(labels, (masks[i] * class_mask).max())
labels = torch.as_tensor(labels, dtype=torch.int64)
#print(boxes,":",labels)
masks = torch.as_tensor(mask_for_all, dtype=torch.uint8)
#print(labels)
#print(masks)
#print(masks.shape)
image_id = torch.tensor([idx])
area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])
# suppose all instances are not crowd
iscrowd = torch.zeros((num_objs,), dtype=torch.int64)
#print(img.shape)
#print(self.imgs[idx])
target = {}
target["boxes"] = boxes
#print(boxes)
target["labels"] = labels
#print(labels.shape)
target["masks"] = masks
#print(masks.shape)
target["image_id"] = image_id
#print(image_id.shape)
target["area"] = area
#print(area)
target["iscrowd"] = iscrowd
#print(iscrowd.shape)
if self.transforms is not None:
img, target = self.transforms(img, target)
return img, target
def __len__(self):
return len(self.imgs)
目录中的文件数,您可以说(注意,我们必须用另一个 '\' 对 '\' 字符进行转义):
C:\
您还可以使用逐字字符串文字转义“\”字符,从而忽略字符串中通常被解释为转义序列的任何内容,即代替 System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("C:\\");
int count = dir.GetFiles().Length;
,您可以说,{{ 1}}
答案 10 :(得分:-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())