两个不同的(?)字符串

时间:2016-06-30 11:16:01

标签: c# string

我注意到两个字符串具有相同(?)内容的行为有惊人的差异。其中一个在方法之外定义,另一个在本地定义。这是代码:

public partial class MainWindow : Window
    {    
    string _outsidethemethod = "bba423c3dd784dff0908";

    public MainWindow()
    {
        InitializeComponent();
    }

    private void button_Click(object sender, RoutedEventArgs e)
        {
            string encoded = Convert.ToBase64String(Encoding.Default.GetBytes("myname:mypass"));
            HttpWebRequest request = WebRequest.Create(_test_website) as HttpWebRequest;

        request.Accept = "application/xml";
        request.Method = "GET";
        request.ContentType = "application/xml";

        CookieContainer cookies = new CookieContainer();
        request.CookieContainer = cookies;

        string auth_string = "Basic " + encoded;
        request.Headers["Authorization"] = auth_string;

        string myAPI = "bba423c3dd784dff0908";
        if (myAPI == _outsidethemethod)
            MessageBox.Show("same");
        else
            MessageBox.Show("different");
        request.Headers.Add("api-key", _outsidethemethod);

     request.ServerCertificateValidationCallback += (sender1, certificate, chain, sslPolicyErrors) => { return true; };

     HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        StreamReader reader = new StreamReader(response.GetResponseStream());

        string xml_response = reader.ReadToEnd();
        reader.Close();
     }
 }

首次尝试使用_outsidethemethod插入标题失败,因为"无效的控制字符"在字符串中。第二次尝试成功(使用_localvariable)虽然字符串内容相同!我已编辑插入确切的代码(用户名/密码/键除外)。唯一的区别是_outsidethemethod属于MainWindow,_localvariable是本地字符串。有什么解释吗?

P.S。我添加了一个字符串比较,尽管内容相同,但字符串似乎有所不同。

我尝试使用以下方法将它们转换为字节数组:

Encoding.Default.GetBytes(thestring)

并且两个字符串给出不同的结果。第一个(包含控制字符的那个)还有3个字符。字符代码是63 ...当我用相同的方法将它们转换回字符串时,我得到一个最后有3个问号的字符串。字符串的其余部分与第二个字符串相同......(工作的字符串)

1 个答案:

答案 0 :(得分:0)

这实际上是Luaan的答案,但因为它从未作为答案发布...

使用二进制编辑器(内置在Visual Studio中)我在字符串中找到隐藏的字符并删除它们。没有隐藏的字符,字符串按预期工作。虽然(并且没有答案)从头开始输入字符串不起作用,这很奇怪!

相关问题