gpt4 book ai didi

VB.NET 遍历文件和目录

转载 作者:行者123 更新时间:2023-12-04 22:37:59 24 4
gpt4 key购买 nike

我正在开发一个 VB.NET 程序,它将自动将我的工作备份到我的 FTP 服务器。到目前为止,我可以通过使用以下命令指定文件名来上传单个文件:

     'relevant part - above is where FTP object is instantiated
Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()

Try
'Stream to which the file to be upload is written
Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()

'Read from the file stream 2kb at a time
Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)

'Till Stream content ends
Do While contentLen <> 0
' Write Content from the file stream to the FTP Upload Stream
_Stream.Write(buff, 0, contentLen)
contentLen = _FileStream.Read(buff, 0, buffLength)
Loop
_Stream.Close()
_Stream.Dispose()
_FileStream.Close()
_FileStream.Dispose()

' Close the file stream and the Request Stream


Catch ex As Exception
MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

现在我希望能够遍历一个目录(其中包含子目录)并递归调用上面的函数。我在获取目录中的文件时遇到问题。

我的问题是,如何遍历每个文件并将其发送到上面的上传功能?我可以将文件名发送到数组,还是有某种系统对象来处理这个问题(例如 System.IO.Directory)

我正在尝试做的伪代码
                For Each Sub_directory In Source_directory

For Each File in Directory
'call the above code to transfer the file
Next

'start next subdirectory
Next

我正在尝试使用完整的子目录复制整个目录结构。我的第一次尝试将所有文​​件都转储到一个目录中。

最佳答案

您可以使用递归遍历每个目录和文件,如下所示:

Public Shared Sub ForEachFileAndFolder(ByVal sourceFolder As String, _
ByVal directoryCallBack As Action(Of DirectoryInfo), _
ByVal fileCallBack As Action(Of FileInfo))

If Directory.Exists(sourceFolder) Then
Try
For Each foldername As String In Directory.GetDirectories(sourceFolder)
If directoryCallBack IsNot Nothing Then
directoryCallBack.Invoke(New DirectoryInfo(foldername))
End If

ForEachFileAndFolder(foldername, directoryCallBack, fileCallBack)
Next
Catch ex As UnauthorizedAccessException
Trace.TraceWarning(ex.Message)
End Try

If fileCallBack IsNot Nothing
For Each filename As String In Directory.GetFiles(sourceFolder)
fileCallBack.Invoke(New FileInfo(filename))
Next
End If
End If
End Sub

编辑:代表的使用:
ForEachFileAndFolder("yourPath", AddressOf dirAction, Addressof fileAction)

Public Sub dirAction(Byval dirInfo As DirectoryInfo)
' do something here '
End Sub

FileAction 也是如此。

关于VB.NET 遍历文件和目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2266551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com