我已经编写了一个运动检测winform c#desktop app。
动画帧作为单独的jpeg保存到我的硬盘中。
我录制了4台摄像机。这由变量表示:
camIndex
每个jpeg都在文件结构下:
c:\ The Year \ The Month \ The Day \ The Hour \ The Minute
确保目录中的每个文件都没有太多文件。
我的目的是让我的应用程序全天候运行。该应用程序可能会因系统重启或用户选择暂时关闭它等原因而停止。
目前,我有一个计时器而不是每5分钟运行一次,以删除超过24小时的文件。
我发现以下代码是内存密集型的,并且在几天的时间内,explorer.exe已经爬进RAM内存。
我的动作应用程序需要一直处于打开状态,因此低内存占用对于这种“归档”至关重要......
以下代码很长,在我看来非常低效。有没有更好的方法来实现我的目标?
我使用此代码:
List<string> catDirs = Directory.EnumerateDirectories(Shared.MOTION_DIRECTORY, "*", SearchOption.TopDirectoryOnly).ToList();
for (int index = 0; index < catDirs.Count; index++)
{
for (int camIndex = 0; camIndex < 4; camIndex++)
{
if (Directory.Exists(catDirs[index] + "\\Catalogues\\" + camIndex.ToString()))
{
List<string> years = GetDirectoryList(catDirs[index] + "\\Catalogues\\" + camIndex.ToString(), true);
if (years.Count == 0)
{
Directory.Delete(catDirs[index]);
}
for (int yearIndex = 0; yearIndex < years.Count; yearIndex++)
{
DirectoryInfo diYear = new DirectoryInfo(years[yearIndex]);
List<string> months = GetDirectoryList(years[yearIndex], true);
if (months.Count == 0)
{
Directory.Delete(years[yearIndex]);
}
for (int monthIndex = 0; monthIndex < months.Count; monthIndex++)
{
DirectoryInfo diMonth = new DirectoryInfo(months[monthIndex]);
List<string> days = GetDirectoryList(months[monthIndex], true);
if (days.Count == 0)
{
Directory.Delete(months[monthIndex]);
}
for (int dayIndex = 0; dayIndex < days.Count; dayIndex++)
{
DirectoryInfo diDay = new DirectoryInfo(days[dayIndex]);
List<string> hours = GetDirectoryList(days[dayIndex], true);
if (hours.Count == 0)
{
Directory.Delete(days[dayIndex]);
}
for (int hourIndex = 0; hourIndex < hours.Count; hourIndex++)
{
DirectoryInfo diHour = new DirectoryInfo(hours[hourIndex]);
List<string> mins = GetDirectoryList(hours[hourIndex], false);
if (mins.Count == 0)
{
Directory.Delete(hours[hourIndex]);
}
for (int minIndex = 0; minIndex < mins.Count; minIndex++)
{
bool deleteMe = false;
DirectoryInfo diMin = new DirectoryInfo(mins[minIndex]);
DateTime foundTS = new DateTime(Convert.ToInt16(diYear.Name), Convert.ToInt16(diMonth.Name), Convert.ToInt16(diDay.Name),
Convert.ToInt16(diHour.Name), Convert.ToInt16(diHour.Name), 00);
double minutesElapsed = upToDateDate.Subtract(foundTS).TotalMinutes;
if (minutesElapsed > diff)
{
deleteMe = true;
}
if (deleteMe)
{
Directory.Delete(mins[minIndex], true);
}
}
}
}
}
}
}
}
答案 0 :(得分:5)
这可能会有所帮助,但不会测试效率:
Directory
.GetFiles(@"[Path of your root directory]", "*.*", SearchOption.AllDirectories)
.Where(item =>
{
try
{
var fileInfo = new FileInfo(item);
return fileInfo.CreationTime < DateTime.Now.AddHours(-24);
}
catch (Exception)
{
return false;
}
})
.ToList()
.ForEach(File.Delete);
确保添加正确的异常处理并避免僵尸尝试/空捕获(不推荐)