我是初学者,正在尝试学习Visual Basic .NET
我有一个包含日志文件的顶级目录。以下是其中一个文件的示例,即文件名生成方法:
Private Property fileDate As String = (Date.Today.ToString("yyyy-MM-dd") & "-" & TimeOfDay.ToString("HH-mm-ss"))
实际生成文件后,最终文件名如下所示: 2015-09-22-17-37-16-MyAppName.log
我希望能够获取日志目录中的所有文件,并删除任何超过x天数的文件。我希望从程序运行的当天起保留7天以内的日志。如果没有大量低效的代码,我无法想到任何方法。
我已经尝试过尝试了解有关FileIO.FileSystem.GetFiles的更多信息..但到目前为止只提出了这个问题:
Dim curDate As Date = Date.Today
Dim subDate As Date = curDate.AddDays(-7)
Dim newDate As String = subDate.ToString("yyyy-MM-dd")
For Each fileFound As String In FileIO.FileSystem.GetFiles("logs",
FileIO.SearchOption.SearchTopLevelOnly,
{newDate & "*"})
Console.WriteLine("FOUND FILE")
Console.WriteLine(fileFound)
Next
但是,当然,只能从当前日期找到名为7天前日期的日志文件。
似乎我需要将logs目录中的所有文件都放到一个数组中,然后从数组中删除任何超过7天的文件。然后最后删除保留在数组中的所有文件?但是如何?
有人可以帮忙吗?非常感谢..
答案 0 :(得分:0)
这是我的尝试。我希望它适合你的目标(它对我有用)。
Dim curDate As Date = Date.Today.ToString("yyyy-MM-dd")
Dim folderPath As String = "Put your path here!"
For Each fileFound As String In Directory.GetFiles(folderPath)
If Regex.IsMatch(fileFound, "\d{4}-\d{2}-\d{2}") Then
Dim regex As Regex = New Regex("\d{4}-\d{2}-\d{2}")
Dim matchFileDate As Match = regex.Match(fileFound)
Dim fileDate As DateTime = DateTime.ParseExact(matchFileDate.Value, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim days As Integer = fileDate.Subtract(curDate).Days
If days < -7 Then
My.Computer.FileSystem.DeleteFile(fileFound)
End If
End If
Next
只有在文件名中始终使用此日期格式yyyy-mm-dd
时才会有效。这是因为正则表达式"\d{4}-\d{2}-\d{2}"
会对其进行调节。但是,你可以找到更好的正则表达式。
答案 1 :(得分:0)
感谢Daro的帖子,我能够得到答案!
这实际上非常简单。我让自己变得比实际上更难。
这是我的解决方案(根据Daro的答案 - 我无法开始工作!! - 抱歉Daro)
请记住,这可能是非常低效的代码,编码练习等,我将在今晚稍后进行清理和整理,但现在是:
Dim curDate As String = Date.Today.ToString("yyyy-MM-dd")
Dim folderPath As String = "logs"
For Each fileFound As String In FileIO.FileSystem.GetFiles(folderPath)
If Regex.IsMatch(fileFound, "\d{4}-\d{2}-\d{2}") Then
Dim regex As Regex = New Regex("\d{4}-\d{2}-\d{2}")
Dim matchFileDate As Match = regex.Match(fileFound)
Dim fileDate As DateTime = DateTime.ParseExact(matchFileDate.Value, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim expDate As Date = CDate(curDate)
expDate = expDate.AddDays(-Me.dayCount)
Console.WriteLine("File found, date: " & CDate(fileDate))
Console.WriteLine("Current file expiration date: " & CDate(expDate))
If CDate(fileDate) < CDate(expDate) Then
Console.WriteLine("This file is older than the expiration date, and will be deleted!")
End If
End If
Next
正则表达式代码可能已经清理了,以及其他东西..但我刚刚开始探索字符串和正则表达式的东西,感谢Daro,以及开始探索如何使用日期。< / p>
谢谢你们!
萨姆