简体   繁体   English

无法获得MyDocuments C#中的子目录和文件的任何文件计数

[英]Cannot get any file count of sub-directories and files in MyDocuments C#

I use the following code to try and count up all the directories and files inside MyDocuments. 我使用以下代码来尝试计算MyDocuments中的所有目录和文件。

This code works with all other special folders (Favorites, Desktop, Photos, etc.) 此代码可用于所有其他特殊文件夹(“收藏夹”,“桌面”,“照片”等)

But when I try to get the count of 'My Documents', it fails. 但是,当我尝试获取“我的文档”的数量时,它失败了。

            /*DOCUMENTS*/               
            documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            fileCount = Directory.GetFiles(documentsFolder, "*.*", SearchOption.AllDirectories).Length; //THIS IS WHERE IT FAILS - DOES NOT GET PAST HERE
            MessageBox.Show(fileCount.ToString()); //THIS NEVER SHOWS

It fails when I try to get the fileCount - which works when I get the counts in other directories. 当我尝试获取fileCount时,它会失败-当我在其他目录中获取计数时,它会起作用。

That directory is fairly large in size on my PC - so maybe I need to 'wait' while it counts? 我的PC上该目录的大小相当大-也许我需要在它计数时“等待”?

I can't figure out why it's not working but all the others work just fine without issue using basically the same code. 我不知道为什么它不起作用,但是所有其他人都可以使用基本相同的代码正常工作而不会出现问题。

Only way I can think of is excluding the folders with no access from the file count 我能想到的唯一方法是从文件数中排除无权访问的文件夹

int fileCount = 0;
var pathToSearch = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

//retrieve files
fileCount += Directory.GetFiles(pathToSearch, "*.*", SearchOption.TopDirectoryOnly).Length;

//retrieve folders
foreach (var subFolder in Directory.GetDirectories(pathToSearch, "*.*", SearchOption.TopDirectoryOnly))
{
    try { Array.ForEach(Directory.GetFiles(subFolder, "*.*", SearchOption.AllDirectories), f => fileCount++); }
    catch { }        
}

MessageBox.Show($"{fileCount}");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用c#列出Linux中的所有子目录 - Cannot list all the sub-directories in Linux using c# 如何使用C#从特定子目录获取文件? - How to get files from a specific sub-directories using c#? 通过C#获取AWS3目录中子目录中的文件名 - Get files names in sub-directories in a directory in AWS3 by C# C#在指定目录和子目录中找到最新创建的* .txt文件? - C# Find the newest created *.txt file in specified directory AND sub-directories? 将文件移到子目录 - Move File To Sub-Directories C#-一种更快的方法来检查目录和子目录是否包含至少一个允许的文件扩展名列表中的文件? - C# - Faster way to check if a directory and sub-directories contain at least 1 file from a list of allowed file extensions? 按日期修改在目录和子目录中复制文件的最快方法 - Fastest way to copy files in directories and sub-directories by datemodified 递归获取具有几个子目录的目录中的文件 - Recursively getting files in a directory with several sub-directories 从Azure容器和子目录获取所有Blob Uris - Get all blob Uris from Azure container and sub-directories C#Streamwriter拒绝将XML文件保存到MyDocuments中的访问 - C# streamwriter denies access to save xml file into MyDocuments
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM