我正在尝试创建一个程序,根据输入和与数据库的匹配创建一堆文件夹。 一切运作良好,但我想以编程方式仔细检查是否创建了正确数量的文件夹。
Private Sub CreateButton_Click(sender As Object, e As EventArgs) Handles CreateButton.Click
Dim rows As DataRow()
rows = dTable.Select(String.Format("[Pick List ID] = '{0}'", PLTextBox.Text))
Dim sourcePath As String = ""
Dim destPath As String = ""
If rows.Count > 0 And PLTextBox.Text <> "" Then
' Some variable i want to use to count the number of folders created.
folderCount = 0
For Each row As DataRow In rows
Try
...
some logic to specify what the sourcePath and destPath will be
...
' Checking if the directory exists
If Not (Directory.Exists(destPath)) Then
Directory.CreateDirectory(destPath)
End If
' Copy pasting source directory into newly created folder
FileIO.FileSystem.CopyDirectory(sourcePath, destPath)
Catch ex As Exception
MsgBox("Error: " & ex.Message,, "Something went wrong...")
End Try
Next
所以在这里,一旦创建了我的所有文件夹,我想验证是否创建了正确的数字,所以在同一个子文件中我有:
RaiseEvent CreationDone(sender, e)
End Sub
要计算我的文件夹,我使用:
Private Sub FSWatcher_Created(sender As Object, e As FileSystemEventArgs) Handles FSWatcher.Created
folderCount = folderCount + 1
End Sub
CreationDone事件是:
Private Sub Creation_Done() Handles Me.CreationDone
Dim rows As DataRow() = dTable.Select(String.Format("[Pick List ID] = '{0}'", PLTextBox.Text))
If folderCount <> rows.Count Then
MsgBox(folderCount & " folders were created. " & rows.Count & " were supposed to be created.",, "Error during the folder creation")
Else
MsgBox(rows.Count & " jobs were created",, "Success!")
End If
End Sub
以下情况发生:
我的CreateButton_Click
处理程序运行后,它会在最后引发CreationDone
事件,但文件夹计数未更新,因为FileSystemWatcher
事件由FSWatcher_Created
处理后CreateButton_Click
完成执行(所以folderCount仍为0)。
我尝试使用事件来执行检查,即引发和处理的事件的顺序是
CreateButton_Click
正在运行对于i = 1到x个文件夹来创建
FSWatcher
提出1个“已创建”事件下
CreationDone
事件被提出CreateButton_Click
结束FSWatcher.Created
个事件CreationDone
但是creationdone优先于文件系统事件。
我该如何解决?
有趣的查找(编辑):当文件夹复制过程中出现异常时,folderCount会正常递增,因此异常是让FSWatcher
引发事件和/或我的代码处理它们。我是否应故意抛出异常才能使其有效? (或者,当我显示msgBox
以显示错误时,它可能就会执行)
谢谢。
答案 0 :(得分:1)
不确定您的代码,如果您尝试获取特定目录的文件夹数量,则可以执行此操作:
Dim folderCount as Integer = Directory.GetDirectories("YourPathway").Length