2012-02-03 57 views
0

我想檢索一些目錄中的所有文件。這是我的原始代碼:獲取文件列表

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 

不過,我得到以下錯誤:

Access to the path 'C:\Users\Simon\AppData\Local\Application Data\' is denied.

有人可以幫助我與我的原代碼,或者幫助我進入這些目錄與我的新代碼?

感謝

編輯:

我加入這個模塊得到它的工作:

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 

前端模塊

+0

好的,全部完成。很容易。我添加了這一行:「如果不是System.IO.Directory.Exists(fileObject.FullName)那麼」 – 2012-02-04 01:27:11

+0

實際上,並非全部完成。我仍然遇到這些錯誤:「訪問路徑'C:\ Users \ UpdatusUser \'被拒絕。」我如何列出這些文件,並複製它們? – 2012-02-04 01:59:19

回答

0

訪問被拒絕的錯誤發生在我認爲的Windows庫上。我不認爲有任何方法列出這些庫中的文件,因爲它們實際上不是文件夾。