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

Ayush JAin

New Member
Joined
Apr 12, 2022
Messages
3
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");
            }

        }
 

Solution
The error should indicate which line is throwing the error.

Most likely though one of the following is not initialized.
Mywriter, Sr or objresponse
The error should indicate which line is throwing the error.

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

Solution
Hello Neemobeer,

Plesae check the error message.
An image from 'Object reference not set to an instance of an object.' Getting this error message'. Code snippet sending a POST request triggers a NullReferenceException on StreamWriter object.
 

Last edited by a moderator:
I would add a break at myWriter = new StreamWriter... and debug and make sure the writer is actually being initialized.
 

I think writer is not initialized, i am not getting any clue ho wto solve this issue, please help me out .Thanks in Advance
An image from 'Object reference not set to an instance of an object.' Getting this error message'. Visual Studio IDE showing C# code handling HTTP POST request and response stream.
 

Last edited by a moderator:
Back
Top