我有这个文件计数功能,它没有返回我父目录的结果。它确实返回所有子目录的结果。在调试期间,我看到父目录作为我的Directory.GetDirectories(sDir)传递,但是一旦它到达Directory.GetFiles(d)它已经改变为子目录。我正撞着这个墙上的一堵墙。显然,它必须是我的foreach循环,但我没有看到它。
我传递的文件结构是:
C:\ Users \ xxxxx \ Desktop \ Temp Logs
但它有三个子目录:
C:\ Users \ xxxxx \ Desktop \ Temp Logs \ sub1
C:\ Users \ xxxxx \ Desktop \ Temp Logs \ sub2
C:\ Users \ xxxxx \ Desktop \ Temp Logs \ sub3
有没有人看到我的错误?
private static string fileCount(string sDir, string sfileType)
{
int count = 0;
string extension;
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string file in Directory.GetFiles(d))
{
extension = Path.GetExtension(file);
if (extension.ToUpper().Equals(sfileType.ToUpper()))
{
TimeSpan fileAge = DateTime.Now - File.GetLastWriteTime(file);
if (fileAge.Days > int.Parse(ConfigurationManager.AppSettings["numberOfDays"]))
{
count++;
}
}
}
}
return count.ToString();
}
答案 0 :(得分:1)
您需要父目录的另一个循环,但在当前循环之外
foreach (string file in Directory.GetFiles(parent_path))
{
extension = Path.GetExtension(file);
if (extension.ToUpper().Equals(sfileType.ToUpper()))
{
TimeSpan fileAge = DateTime.Now - File.GetLastWriteTime(file);
if (fileAge.Days > int.Parse(ConfigurationManager.AppSettings["numberOfDays"]))
{
count++;
}
}
}
答案 1 :(得分:0)
您在foreach中使用的数组仅包含子目录。添加父母和你的好去!
private static string fileCount(string sDir, string sfileType)
{
int count = 0;
string extension;
List<string> directoriesToCheck = Directory.GetDirectories(sDir).ToList();
directoriesToCheck.Add(sDir);
foreach (string d in directoriesToCheck)
{
foreach (string file in Directory.GetFiles(d))
{
extension = System.IO.Path.GetExtension(file);
if (extension.ToUpper().Equals(sfileType.ToUpper()))
{
TimeSpan fileAge = DateTime.Now - File.GetLastWriteTime(file);
if (fileAge.Days > int.Parse(ConfigurationManager.AppSettings["numberOfDays"]))
{
count++;
}
}
}
}
return count.ToString();
}