Why String.Equals is returning false?

故事扮演 提交于 2019-12-17 19:27:12

问题


I have the following C# code (from a library I'm using) that tries to find a certificate comparing the thumbprint. Notice that in the following code both mycert.Thumbprint and certificateThumbprint are strings.

var certificateThumbprint = AppSettings.CertificateThumbprint;

var cert =
    myStore.Certificates.OfType<X509Certificate2>().FirstOrDefault(
      mycert => 
      mycert.Thumbprint != null && mycert.Thumbprint.Equals(certificateThumbprint)
      );

This fails to find the certificate with the thumbprint because mycert.Thumbprint.Equals(certificateThumbprint) is false even when the strings are equal. mycert.Thumbprint == certificateThumbprint also returns false, while mycert.Thumbprint.CompareTo(certificateThumbprint) returns 0.

I might be missing something obvious, but I can't figure out why the Equals method is failing. Ideas?


回答1:


CompareTo ignores certain characters:

static void Main(string[] args)
{
    var a = "asdas"+(char)847;//add a hidden character
    var b = "asdas";
    Console.WriteLine(a.Equals(b)); //false
    Console.WriteLine(a.CompareTo(b)); //0
    Console.WriteLine(a.Length); //6
    Console.WriteLine(b.Length); //5

   //watch window shows both a and b as "asdas"
}

(Here, the character added to a is U+034F, Combining Grapheme Joiner.)

So CompareTo's result is not a good indicator of a bug in Equals. The most likely reason of your problem is hidden characters. You can check the lengths to be sure.

See this for more info.




回答2:


You may wish to try using an overload of String.Equals that accepts a parameter of type StringComparison.

For example:

myCert.Thumbprint.Equals(certificateThumbprint, StringComparison.[SomeEnumeration])


Where [SomeEnumeration] is replaced with one of the following enumerated constants:

 - CurrentCulture
 - CurrentCultureIgnoreCase
 - InvariantCulture
 - InvariantCultureIgnoreCase
 - Ordinal
 - OrdinalIgnoreCase


Reference the MSDN Documentation found here.




回答3:


Sometimes when we insert data in database it stores some spaces like "question ". And when you will try to compare it with "question" it returns false. So my suggestion is: please check the value in database or use Trim() method.

In your case, please try: mycert.Thumbprint != null && mycert.Thumbprint.trim().equals(certificateThumbprint.trim())

I think it will return true if any record will exist.



来源:https://stackoverflow.com/questions/25999031/why-string-equals-is-returning-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!