正如标题所说,任何人都知道如何克服这个错误?这是我的第一个使用visual basic的程序,似乎无法找到答案......
尝试
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles GetProfiles_Button.Click
For Each fileName As String In FileIO.FileSystem.GetDirectories("C:\", FileIO.SearchOption.SearchAllSubDirectories)
CheckedListBox1.Items.Add(fileName)
On Error Resume Next
Next
End Sub
End Class
我试过
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles GetProfiles_Button.Click
Try
For Each fileName As String In FileIO.FileSystem.GetDirectories("C:\", FileIO.SearchOption.SearchAllSubDirectories)
CheckedListBox1.Items.Add(fileName)
Next
Catch ex As UnauthorizedAccessException
MsgBox("Unable to access " & ex.Message)
End Try
End Sub
End Class
我认为我可以通过创建一个测试每个文件夹的循环来解决这个问题,但是代码要多得多,效率也很低......有什么建议吗?
答案 0 :(得分:1)
您可以在GetFiles
或GetDirectories
等文件方法上获得多个例外。
一些可能的例外(from)
您必须手动迭代所有文件和文件夹:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim allCFileName = FindAllFiles("C:\")
For Each fileName As String In allCFileName
CheckedListBox1.Items.Add(fileName)
Next
End Sub
Public Shared Function FindAllFiles(rootDir As String) As String()
Dim paths = New Queue(Of String)()
Dim fileNames = New List(Of String)()
paths.Enqueue(rootDir)
While paths.Count > 0
Dim dir = paths.Dequeue()
Try
Dim files = Directory.GetFiles(dir)
For Each file As String In Directory.GetFiles(dir)
fileNames.Add(file)
Next
For Each subDir As String In Directory.GetDirectories(dir)
paths.Enqueue(subDir)
Next
Catch unauthorizedAccessException As UnauthorizedAccessException
' log the exception or ignore it
Console.WriteLine("Directory {0} could not be accessed!", dir)
Catch generalException As Exception
' log the exception or ...
Throw
End Try
End While
Return fileNames.ToArray()
End Function
答案 1 :(得分:0)
Try
For Each path As String In filePath
If File.Exists(path) Then
' This path is a file
ProcessFile(path)
ElseIf Directory.Exists(path) Then
' This path is a directory
ProcessDirectory(path)
Else
Console.WriteLine("{0} is not a valid file or directory.", path)
End If
Next
Catch ex As UnauthorizedAccessException
MsgBox("Unable to access " & ex.Message)
End Try
Public Shared Sub ProcessDirectory(targetDirectory As String)
' Process the list of files found in the directory.
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
For Each fileName As String In fileEntries
ProcessFile(fileName)
Next
' Recurse into subdirectories of this directory.
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
For Each subdirectory As String In subdirectoryEntries
ProcessDirectory(subdirectory)
Next
End Sub
Public Shared Sub ProcessFile(path As String)
File.Exists(path)
End Sub
这将访问所有目录,子目录和文件。如果您无权访问该文件,Files.Exists应返回false,因此您还应检查该文件。