Vb.net 检查字符串是否包含stringarray(vb net)的任何元素
我有个小问题。在程序结束时,它应该删除一个文件夹 为了拒绝删除包含某个单词的文件夹,我想检查字符串(directory.fullname.tostring)是否包含存储在字符串数组中的任何元素。 字符串数组包含声明异常字的字符串 这就是我所取得的成绩,我知道解决方案与此处所述相反:Vb.net 检查字符串是否包含stringarray(vb net)的任何元素,vb.net,string,compare,contains,arrays,Vb.net,String,Compare,Contains,Arrays,我有个小问题。在程序结束时,它应该删除一个文件夹 为了拒绝删除包含某个单词的文件夹,我想检查字符串(directory.fullname.tostring)是否包含存储在字符串数组中的任何元素。 字符串数组包含声明异常字的字符串 这就是我所取得的成绩,我知道解决方案与此处所述相反: If Not stackarray.Contains(dir.FullName.ToString) Then Try dir.Delete()
If Not stackarray.Contains(dir.FullName.ToString) Then
Try
dir.Delete()
sw.WriteLine("deleting directory " + dir.FullName, True)
deldir = deldir + 1
Catch e As Exception
'write to log
sw.WriteLine("cannot delete directory " + dir.ToString + "because there are still files in there", True)
numbererror = numbererror + 1
End Try
Else
sw.WriteLine("cannot delete directory " + dir.ToString + "because it is one of the exception directories", True)
End If
与其检查数组是否包含完整路径,不如反过来检查。循环遍历数组中的所有项,并检查路径是否包含每个项,例如:
Dim isException As Boolean = False
For Each i As String In stackarray
If dir.FullName.ToString().IndexOf(i) <> -1 Then
isException = True
Exit For
End If
Next
If isException Then
' ...
End If
Dim isException为布尔值=False
对于stackarray中的每个i As字符串
如果dir.FullName.ToString().IndexOf(i)-1,则
isException=True
退出
如果结束
下一个
如果是例外的话
' ...
如果结束
或者,如果您想更别致一些,可以使用Array.Exists方法以更少的代码行完成此操作,如下所示:
If Array.Exists(stackarray, Function(x) dir.FullName.ToString().IndexOf(x) <> -1) Then
' ...
End If
如果Array.Exists(stackarray,函数(x)dir.FullName.ToString().IndexOf(x)-1),则
' ...
如果结束
试试这个:
foldersToDelete.Any(Function(folder) dir.ToLower.Contains(folder.ToLower)
您可以查看更多信息
我想检查字符串(directory.fullname.tostring)是否包含存储在字符串数组中的任何元素
。。比如什么?这些元素是文件夹路径。例如“D:\stuff\u not\u to\u delete”。您的代码没有按预期工作。。哪一部分?第一行没有预期的效果。我应该反过来工作。预期的方法是:程序应检查directory.fullname的字符串是否包含任何元素,如果包含,则不应执行任何操作,否则应尽可能删除文件夹。现在它检查,如果数组包含dir.fullname字符串,并且没有预期的效果…我认为使用就足够了,如果不是stackarray.contains(dir.fullname),那么。。