【问题标题】:check if string contains any of the elements of a stringarray (vb net)检查字符串是否包含字符串数组的任何元素(vb net)
【发布时间】:2013-09-27 23:29:20
【问题描述】:

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

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

这就是我得到的结果,我知道解决方案与此处所述相反:

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

【问题讨论】:

  • I wanted to check if a string (the directory.fullname.tostring) contains any of the elements which are stored in a string array..比如什么?
  • 这些元素是文件夹路径。比如“D:\stuff_not_to_delete”。
  • 您的代码没有按预期工作? ..哪一部分?
  • 第一行没有按预期工作。我应该反过来工作。预期的方法是:程序应检查 directory.fullname 的字符串是否包含任何元素,如果包含,则不应执行任何操作,否则应尽可能删除文件夹。现在它检查数组是否包含 dir.fullname 字符串并且没有预期的效果......
  • 我认为If Not stackarray.Contains(dir.FullName) Then 应该足够了..

标签: vb.net string compare contains arrays


【解决方案1】:

与其检查数组是否包含完整路径,不如反其道而行之。循环遍历数组中的所有项并检查路径是否包含每一项,例如:

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 方法用更少的代码来完成,像这样:

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

【讨论】:

    【解决方案2】:

    试试这个:

    foldersToDelete.Any(Function(folder) dir.ToLower.Contains(folder.ToLower)
    

    您可以查看更多信息here

    【讨论】:

      猜你喜欢
      • 2019-03-13
      • 2011-12-23
      • 2013-10-03
      • 2015-09-08
      • 2016-09-22
      • 2021-05-02
      • 1970-01-01
      • 2019-10-22
      相关资源
      最近更新 更多