如何检查字符串是否包含其他两个字符串

时间:2015-07-31 13:57:55

标签: c# .net string

我有一个包含异常消息的变量。如何检查异常消息文本是否是这样的:

 var ex.message = "Cannot open server 'abcd' requested by the login";

请注意,服务器名称可以是任意长度吗?

6 个答案:

答案 0 :(得分:3)

您不应该使用异常消息来确定出错的地方。而是捕获相关的异常类型并在那里处理它。例如,您可能会使用SqlException

try
{
    ConnectToDatabase();
}
catch(SqlException ex)
{
    //Now we know a SQL exception has occurred, perhaps check the Number property?
    if(ex.Number == 18456) 
    {
        //Login failed
    }
}
catch(Exception ex)
{
    //General exception handling goes here
}

答案 1 :(得分:2)

您可以使用正则表达式

执行此操作
.crossed {
   fill: orange !important;
}

答案 2 :(得分:1)

string.Contains("string")

Documentation

答案 3 :(得分:1)

ex.message.Contains("Cannot open server") && ex.message.Contains("requested by the login")

答案 4 :(得分:1)

ex.message.StartsWith("Cannot open server") && ex.message.EndsWith("requested by the login")

如果您已经知道服务器名称,也可以检查中间的内容。

为什么不做得更好并定义自己的自定义异常。例如ServerConnectionFailedException

答案 5 :(得分:1)

有点奇特的解决方案(通过 extesnion方法):

  public static class Strings {
    public static Boolean ContainsAll(this String source, params String[] toFind) {
      if (null == toFind)
        return true; // or throw an exception
      else if (toFind.Length <= 0)
        return true;

      if (String.IsNullOrEmpty(source))
        return false;

      foreach (var item in toFind)
        if (!source.Contains(item))
          return false;

      return true;
    }
  }

  ...

  var ex.message = "Cannot open server 'abcd' requested by the login";

  if (ex.message.ContainsAll("Cannot open server", "requested by the login")) {
    ...
  }
相关问题