Reputation: 11
I have this file count function that is not returning results from my parent directory. It does return results of all sub directories. During my debugging I def see the parent directory being passed as my Directory.GetDirectories(sDir) but once it hits Directory.GetFiles(d) it already changed to the sub directories. I am banging my head against a wall on this one. Clearly, it must be my foreach loop but I am not seeing it.
The file structure I am passing is:
C:\Users\xxxxx\Desktop\Temp Logs
but it has three sub directories:
C:\Users\xxxxx\Desktop\Temp Logs\sub1
C:\Users\xxxxx\Desktop\Temp Logs\sub2
C:\Users\xxxxx\Desktop\Temp Logs\sub3
Does anyone see my error?
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();
}
Upvotes: 0
Views: 173
Reputation: 461
The array you use in the foreach only contains SubDirectories. Add the parent and your good to go!
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();
}
Upvotes: 0
Reputation: 362
You need another loop for the parent directory but outside you current loop
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++;
}
}
}
Upvotes: 1