我有一个外部硬盘驱动器用于数据备份。现在我要删除该驱动器中的所有mp3文件。我该怎么做?
注意:mp3文件包含在许多嵌套文件夹中。例如,K:\(artist name)\(album name)\
个mp3文件
更新:我尝试使用system.io.directory.getallfiles()
,但我的mp3文件包含在很多文件夹中。我目前的方法不起作用
更新:我想创建一个可以删除特定文件扩展名的实用程序应用程序(在winform中),即.mp3
答案 0 :(得分:2)
我不熟悉VB.NET,因此只能指出要使用的功能:
GetFiles
SearchOption.AllDirectories
File.Delete
在每一个。这将是这样的(抱歉,如果有一些错误):
Try
For Each f In Directory.GetFiles("F:\", "*.mp3", SearchOption.AllDirectories)
File.Delete(f)
Next
Catch ex As UnauthorizedAccessException
End Try
了解MSDN上的例外情况。
答案 1 :(得分:1)
好的,考虑到正在追求的长链评论,我决定在VS中编写一个片段,这是我的工作代码。希望这能解决你的问题。再次,请记住,这不涉及符号链接循环,但我强烈怀疑你将在你的文件夹中有那些;否则有时间阅读!
For Each folder In Directory.GetDirectories("D:\")
Try
For Each filePath In Directory.GetFiles(folder, "*.mp3", SearchOption.AllDirectories)
'I'll just print the mp3 file found but of course you can delete it in your folder
Debug.WriteLine(String.Format("{0}", filePath))
'File.Delete(filePath)
Next
Catch ex As UnauthorizedAccessException
'Report your exception here if you need to. I'm just ignoring it
End Try
Next
答案 2 :(得分:1)
Imports System
Imports System.IO
Imports System.Collections
Public Class RecursiveFileProcessor
Public Overloads Shared Sub Main(ByVal args() As String)
Dim path As String
For Each path In args
If File.Exists(path) Then
' This path is a file.
ProcessFile(path)
Else
If Directory.Exists(path) Then
' This path is a directory.
ProcessDirectory(path)
End If
End If
Next path
End Sub 'Main
' Process all files in the directory passed in, recurse on any directories
' that are found, and process the files they contain.
Public Shared Sub ProcessDirectory(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
' Process the list of files found in the directory.
Dim fileName As String
For Each fileName In fileEntries
ProcessFile(fileName)
Next fileName
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
' Recurse into subdirectories of this directory.
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
ProcessDirectory(subdirectory)
Next subdirectory
End Sub 'ProcessDirectory
' Insert logic for processing found files here.
Public Shared Sub ProcessFile(ByVal path As String)
if path.EndsWith(".mp3") then DeleteFile(path)
End Sub 'ProcessFile
End Class 'RecursiveFileProcessor
答案 3 :(得分:0)
我为你写了一个课,但是在c#:)你可以轻松地将它转换为VB.net
Imports System.IO
Module Module1
Sub Main()
Dim d As New DirectoryInfo("d:\")
deleteMp3File(d)
End Sub
Public Sub deleteMp3File(ByVal directory As DirectoryInfo)
For Each f As FileInfo In directory.GetFiles()
If f.Extension.ToLower().Equals("mp3") Then
deleteFile(f.FullName)
End If
Next
Dim obj As DirectoryInfo() = directory.GetDirectories()
If obj IsNot Nothing AndAlso obj.Count() > 0 Then
For Each d As DirectoryInfo In obj
deleteMp3File(d)
Next
End If
End Sub
Public Sub deleteFile(ByVal path As String)
File.Delete(path)
End Sub
End Module