Input string was not in a correct format

Asked

Viewed 3,224 times

3

When calling the method below comes the message

the input character 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);
            }
        }
  • Can you give me an example of input that causes this error?

1 answer

5


This is a common mistake. People think that converting string in another kind will always work. If the data is not controlled by you, that is if it comes from an uncertain external source, like typing for example, you cannot trust what comes, you have to try to convert and check whether it worked or not. Then I’d 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 put in the Github for future reference.

If you are using C# 7 it can be 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.