我有这段代码
Private Sub DeleteOldFiles(
ByVal AsDirectoryName As String,
ByVal AbDeleteSubDirectories As Boolean,
ByVal AbDeleteFolders As Boolean)
If AbDeleteSubDirectories Then
Dim m_sSubdirectoryName As String
For Each m_sSubdirectoryName In
System.IO.Directory.GetDirectories(AsDirectoryName)
DeleteOldFiles _
(m_sSubdirectoryName,
AbDeleteSubDirectories,
AbDeleteFolders)
If AbDeleteFolders Then
System.IO.Directory.Delete(m_sSubdirectoryName)
End If
Next
End If
Dim m_sFileName As String
For Each m_sFileName In
System.IO.Directory.GetFiles(AsDirectoryName)
If m_sFileName <> "p2ptv_preview01.zip" Then
System.IO.File.Delete(m_sFileName)
End If
Next
按钮控件上的和DeleteOldFiles(&#34; ./",True,True)。 但是,此代码仅适用于一个文件。 我想除了更多的文件。 我怎么能这样做?
答案 0 :(得分:2)
只需传入您不想删除的豁免文件列表,然后查看当前文件名是否在该列表中。
Private Sub DeleteOldFiles(
ByVal AsDirectoryName As String,
ByVal AbDeleteSubDirectories As Boolean,
ByVal AbDeleteFolders As Boolean,
ByVal exemptFileNames As IEnumerable(Of String))
If AbDeleteSubDirectories Then
Dim m_sSubdirectoryName As String
For Each m_sSubdirectoryName In
System.IO.Directory.GetDirectories(AsDirectoryName)
DeleteOldFiles _
(m_sSubdirectoryName,
AbDeleteSubDirectories,
AbDeleteFolders,
exemptFileNames)
If AbDeleteFolders Then
System.IO.Directory.Delete(m_sSubdirectoryName)
End If
Next
End If
Dim m_sFileName As String
For Each m_sFileName In
System.IO.Directory.GetFiles(AsDirectoryName)
If exemptFileNames.Contains(m_sFileName) Then
Console.WriteLine("Skipped " & m_sFileName)
Else
System.IO.File.Delete(m_sFileName)
End If
Next
End Sub
用法:
Sub Main()
Dim exemptFilenames As New List(Of String)()
exemptFilenames.Add("p2ptv_preview01.zip")
exemptFilenames.Add("name2.txt")
exemptFilenames.Add("name3.tar")
DeleteOldFiles("./", True, True, exemptFilenames)
End Sub