[英]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.