Windows 7 Object reference not set to an instance of an object." Getting this error message

Ayush JAin

New Member
Hello Team,

I am using API in my desktop windows application and while clicking on Send button Getting this Error message "Object reference not set to an instance of an object." previously this below code was working fine.

C#:
private void btn_Send_Click(object sender1, EventArgs e1)
        {
            String result;
            string apiKey = "Zs3TRsRIFCs-tRyNcGbbKpVO8otloaz2lspUS44tBk";
            string numbers = txt_Contactno.Text;
            string message = txt_MessageBox.Text;
            string sender = "DASHAN";

            String url = "https://api.textlocal.in/send/?apikey=" + apiKey + "&numbers=" + numbers + "&message=" + message + "&sender=" + sender;
            //refer to parameters to complete correct url string

            StreamWriter myWriter = null;         
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);

            objRequest.Method = "POST";
            objRequest.ContentLength = Encoding.UTF8.GetByteCount(url);
            objRequest.ContentType = "application/x-www-form-urlencoded";
            try
            {
                myWriter = new StreamWriter(objRequest.GetRequestStream());
                myWriter.Write(url);
            }
            catch (Exception e)
            {

            }
            finally
            {
                myWriter.Close();
            }
            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
            {
                result = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
                MessageBox.Show("Message Sent");
            }

        }
 

Neemobeer

Principal Cybersecurity Architect
Staff member
The error should indicate which line is throwing the error.

Most likely though one of the following is not initialized.
Mywriter, Sr or objresponse
 

Ayush JAin

New Member
Hello Neemobeer,

Plesae check the error message.
1650112659329.png
 

Neemobeer

Principal Cybersecurity Architect
Staff member
I would add a break at myWriter = new StreamWriter... and debug and make sure the writer is actually being initialized.
 
Top