vb.net - For Each Loop in VB.net 卡在条件语句中
问题描述
我正在尝试使用 vb.net 编写代码,但我陷入了一个For Each
循环,我希望有人能提供帮助。
我正在尝试按扩展名搜索文件,我使用了For Each
如下循环:
For Each XMLLFILE In Directory.GetFiles(directoryName, "*.xmll", SearchOption.TopDirectoryOnly)
之后,我尝试添加一个条件来删除搜索到的文件,如果没有,则弹出一条消息,指出没有找到文件。其余的代码是:
If My.Computer.FileSystem.FileExists(XMLLFILE) Then
File.Delete(XMLLFILE)
MsgBox("Files Deleted !", vbOKOnly, "DeleteXMLL Files")
Else
MsgBox("There's No files to be Deleted !", vbOKOnly, "DeleteXMLL Files")
End If
Exit For
Next
End If
每次删除文件(重复)时,我都会收到一个消息框,如果文件夹内没有文件,我根本没有消息框。
任何人都可以帮助代码吗?
解决方案
该GetFiles()
方法返回该文件夹中确实存在的文件。您的If
语句检查每个文件是否存在,这没有意义(因为我们已经知道它们存在)。相反,您应该检查是否GetFiles()
返回任何文件。
尝试以下操作:
' Find the files and store them in a String array.
Dim filesToDelete As String() =
Directory.GetFiles(directoryName, "*.xmll", SearchOption.TopDirectoryOnly)
' If some files are found,...
If filesToDelete.Any() Then
' Delete each one of them...
For Each XMLLFILE In filesToDelete
File.Delete(XMLLFILE)
Next
' ..and then display a success message.
MsgBox("Files Deleted!", vbOKOnly, "DeleteXMLL Files")
Else
' If not, display a different message.
MsgBox("There are No files to be Deleted!", vbOKOnly, "DeleteXMLL Files")
End If
推荐阅读
- reactjs - 如何将道具传递给函数内部的组件?
- javascript - 将多个等待变量组合成一个数组
- python - 如何在 python 中的 Outlook 上向多个人发送电子邮件?
- reactjs - 在 IE10 中反应未定义的地图
- react-native - React-Navigation 5 TypeError:无法读取未定义的属性'_context' 此错误位于forwardRef(BaseNavigationContainer)
- java - 如何实现在 X 分钟内未收到任何事件后发出的 Flink 事件时间触发器
- c# - Discord.NET 从一个控制台应用程序项目运行多个机器人
- reactjs - 命令 create-react-app 不运行,它会产生错误
- javascript - 基于另一个 CSS 样式元素的 Javascript 内联旋转变换样式
- javascript - 将 PHP 变量传递给 javascript,包括引号和 javascript