获取文件列表

时间:2012-02-03 23:24:19

标签: vb.net

我想要检索某些目录中的所有文件。这是我的原始代码:

    Private Function Search(path As String, Recursive As Boolean) As Boolean
    Dim dirInfo As New IO.DirectoryInfo(path)
    Dim fileObject As FileSystemInfo

    If Recursive = True Then
        For Each fileObject In dirInfo.GetFileSystemInfos()
            If fileObject.Attributes = FileAttributes.Directory Then
                Search(fileObject.FullName, Recursive)
            Else
                lstFiles.Items.Add(fileObject.FullName)
            End If
        Next
    Else
        For Each fileObject In dirInfo.GetFileSystemInfos()
            lstFiles.Items.Add(fileObject.FullName)
        Next
    End If

    Return True
End Function

此代码运行良好,但它返回一些目录,我只想返回文件。

我试过这段代码:

    Private Sub Search(ByVal path As String, ByVal Recursive As Boolean)   
    if not Directory.Exists(path) then Exit Sub

    Dim initDirInfo As New DirectoryInfo(path)

    For Each oFileInfo In initDirInfo.GetFiles
        lstfiles.items.add(oFileInfo.Name)
    Next

    If Recursive Then
        For Each oDirInfo In initDirInfo.GetDirectories
            Search(oDirInfo.FullName, True)
        Next
    End If
End Sub 

但是,我收到以下错误:

  

拒绝访问路径'C:\ Users \ Simon \ AppData \ Local \ Application Data \'。

有人可以帮助我使用原始代码,还是帮我用新代码访问这些目录?

感谢

编辑:

我已添加此模块以使其正常工作:

Imports System.Security.Principal

模块VistaSecurity

'Declare API
Private Declare Ansi Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As String) As Integer
Private Const BCM_FIRST As Int32 = &H1600
Private Const BCM_SETSHIELD As Int32 = (BCM_FIRST + &HC)

Public Function IsVistaOrHigher() As Boolean
    Return Environment.OSVersion.Version.Major < 6
End Function

' Checks if the process is elevated
Public Function IsAdmin() As Boolean
    Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
    Dim p As WindowsPrincipal = New WindowsPrincipal(id)
    Return p.IsInRole(WindowsBuiltInRole.Administrator)
End Function

' Add a shield icon to a button
Public Sub AddShieldToButton(ByRef b As Button)
    b.FlatStyle = FlatStyle.System
    SendMessage(b.Handle, BCM_SETSHIELD, 0, &HFFFFFFFF)
End Sub

' Restart the current process with administrator credentials
Public Sub RestartElevated()
    Dim startInfo As ProcessStartInfo = New ProcessStartInfo()
    startInfo.UseShellExecute = True
    startInfo.WorkingDirectory = Environment.CurrentDirectory
    startInfo.FileName = Application.ExecutablePath
    startInfo.Verb = "runas"
    Try
        Dim p As Process = Process.Start(startInfo)
    Catch ex As Exception
        Return 'If cancelled, do nothing
    End Try
    Application.Exit()
End Sub

结束模块

1 个答案:

答案 0 :(得分:0)

我认为在Windows库中发生访问被拒绝错误。我认为没有办法在这些库中列出文件,因为它们实际上并不是文件夹。