检查string是否包含stringarray(vb net)的任何元素 [英] check if string contains any of the elements of a stringarray (vb net)

查看:60
本文介绍了检查string是否包含stringarray(vb net)的任何元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题。在程序结束时,应删除一个文件夹。

I´ve got a little problem. At the end of a programm it should delete a folder.

为了拒绝删除包含某个单词的目录,我想检查是否有字符串(directory.fullname.tostring)包含存储在字符串数组中的任何元素。
字符串数组包含说明异常词的字符串。

In ordern to deny deletion of a folder, which directory contains a certain word, I wanted to check if a string (the directory.fullname.tostring) contains any of the elements which are stored in a string array. The string array contains strings stating the exception words.

这是我所走的距离,我知道解决方案与此处所说的相反:

This is how far I got and I know that the solution is the other way round than stated here:

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


推荐答案

而不是o f检查数组是否包含完整路径,反之亦然。循环遍历数组中的所有项目,并检查路径是否包含每个项目,例如:

Instead of checking to see if the array contains the full path, do it the other way around. Loop through all the items in the array and check if the path contains each one, for instance:

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

或者,如果您想花更多的钱,可以使用Array.Exists方法减少花费代码行,例如:

Or, if you want to be more fancy, you can use the Array.Exists method to do it with less lines of code, like this:

If Array.Exists(stackarray, Function(x) dir.FullName.ToString().IndexOf(x) <> -1) Then
    ' ...
End If

这篇关于检查string是否包含stringarray(vb net)的任何元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆