The input string was not in a correct format

1

When calling the method below comes the message

  

the input string was not in a correct format

private void SubmitData()
        {
            try
            {
                string user = usuario.Text;
                string pass = senha.Text;

                ASCIIEncoding encoding = new ASCIIEncoding();
                string postData = "username=" + user + "&password=" + pass;
                byte[] data = encoding.GetBytes(postData);

                WebRequest request = WebRequest.Create("url do site/auth?username=" + user + "&password=" + pass + "");


                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;

                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();

                WebResponse response = request.GetResponse();
                stream = response.GetResponseStream();

                StreamReader sr = new StreamReader(stream);
                int resultado = int.Parse(sr.ReadLine());
                // MessageBox.Show(resultado.ToString());

                if (resultado == 1)
                {
                    Form1 segundo = new Form1();
                    this.Hide();
                    segundo.ShowDialog();



                }
                else
                {
                    MessageBox.Show("Your time expired");

                    usuario.ResetText();
                    senha.ResetText();
                }

                sr.Close();
                stream.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
        }
    
asked by anonymous 15.06.2017 / 15:43

1 answer

2

This is a common mistake. People think converting string to something else will always work. If the data is not controlled by you, that is if it comes from an external source, such as typing, for example, you can not trust what's next, you have to try to convert it and check it worked out or not. Then you would need to change to:

var sr = new StreamReader(stream);
int resultado;
MessageBox.Show(int.TryParse(sr.ReadLine(), out resultado) ? resultado : "Deu algum erro no dado recebido");

I placed GitHub for futur reference a.

If you are using C # 7 it might look like this:

var sr = new StreamReader(stream);
MessageBox.Show(int.TryParse(sr.ReadLine(), out var resultado) ? resultado : "Deu algum erro no dado recebido");

See more in Differences between Parse vs TryParse .

    
15.06.2017 / 16:08