【问题标题】:VB - If StreamReader reads line containing ("string1") but missing ("string2")VB - 如果 StreamReader 读取包含 ("string1") 但缺少 ("string2") 的行
【发布时间】:2015-07-23 17:47:01
【问题描述】:

编辑: 我将如何检索满足上述条件的文件的文件名?

如何检查字符串是否包含“value1”但不包含“value2”?我试过这个:

While Not sr.EndOfStream
    Dim sLine As String = sr.ReadLine
    If sLine.Contains("value1") Then
        If Not sLine.Contains("value2") Then
            sw.WriteLine("write name of file that meets conditions to txt file")
End While

不确定如何搜索缺失值。

【问题讨论】:

  • 您在寻找AndNot 吗? (见en.wikibooks.org/wiki/Visual_Basic_.NET/Logical_operators#And
  • 单行还是整个文件?
  • 根据这些条件搜索整个文件
  • 你试过 If sLine.Contains("value1") And Not sLine.Contains("value2") 吗?
  • 因此,如果第 1 行包含单词 'value1' 并且第 10 行包含单词 'value2' 您找到了正确的文件,否则如果缺少两个值之一,您有错误吗?

标签: vb.net string contains


【解决方案1】:

您可以将整个文件加载到一个字符串中并进行检查

If wholeFileData.Contains("value1") AndAlso Not wholeFileData.Contains("value2") Then
    sw.WriteLine("write name of file that meets conditions to txt file")
End If

如果您需要循环每一行,那么您需要存储在一个变量中并在最后显示消息。

Dim containsValue1, containsValue2 As Boolean

containsValue1 = False
containsValue2 = False

While Not sr.EndOfStream
    Dim sLine As String = sr.ReadLine

    If sLine.Contains("value1") Then
        containsValue1 = True
    End If

    If sLine.Contains("value2") Then
        containsValue2 = True
    End If
End While

If containsValue1 AndAlso Not containsValue2 Then
    sw.WriteLine("write name of file that meets conditions to txt file")
End If

【讨论】:

  • 非常感谢!从读取的文件中检索文件名的最佳方法是什么?
  • @Gmac 我无法知道您是如何打开文件的(它可能来自 TCP/IP 流)。
【解决方案2】:
If sLine.Contains("value1") = True and sLine.Contains("value2") = False Then
    Msgbox("sLine contains value1, but does not contain value2")
End If

【讨论】:

    猜你喜欢
    • 2017-10-17
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    相关资源
    最近更新 更多