有一列表c:\list.txt(内容不重复),文件夹c:\MP3内有若干MP3文件,如何删除列表以外的文件
list.txt内容如下,
ASDFG.MP3
ADDFG.MP3
ASFFG.MP3
ASHFG.MP3
------解决思路----------------------
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim list() As String
Dim listFile As String = "C:\list.txt"
If Not File.Exists(listFile) Then
MessageBox.Show("不存在此文件夹")
Exit Sub
End If
'读列表文件内容
list = File.ReadAllLines(listFile)
If list.Length = 0 Then
MessageBox.Show("文件中不存在内容")
Exit Sub
End If
DeleteFile(List)
End Sub
Private Sub DeleteFile(ByVal list As String())
Try
Dim path As String = "C:\MP3"
If Not Directory.Exists(path) Then
MessageBox.Show("不存在此文件夹")
Exit Sub
End If
Dim fileAll() As String = Directory.GetFiles(path)
For Each filestr As String In fileAll
Dim startIndex As Integer = InStrRev(filestr, "\")
Dim compareFile As String = filestr.Substring(startIndex, filestr.Length - startIndex)
Dim flag As Boolean = False '加次标志,判断此文件是否在list中
For Each str As String In list
If filestr = str Then '判断文件夹中文件和list内容是否相等
flag = True
End If
Next
'如果没有相等的则删除
If flag = False Then
File.Delete(filestr)
End If
Next
MessageBox.Show("删除成功")
Catch ex As Exception
MessageBox.Show("删除出错")
End Try
End Sub
End Class