Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a webpage that need to pass data to web Service (SMS) and I tried to use WebRequest to do this work but when I use this class the following error appears:

Cannot close stream until all bytes are written
in the line after this line :

stOut.WriteLine(strNewValue,number,text);
What is the problem? I tried to use Flush() but didn't work either
C#
public class SendSms
{
    public SendSms(string number, string text)
    {
         string strNewValue;
         string strResponse;

         HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.buymessage.com/ostazSms/send.php");          

         req.Method = "POST";
         req.ContentType = "application/x-www-form-urlencoded";
         strNewValue = "usr=****&pwd=*****&to={0}&msg={1}"; 
         req.ContentLength = strNewValue.Length;

         using(StreamWriter stOut = new StreamWriter (req.GetRequestStream(), System.Text.Encoding.Unicode))
         {
             stOut.WriteLine(strNewValue,number,text);
         }

        StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
        strResponse = stIn.ReadToEnd();
        stIn.Close();  
    }
}
Posted
Updated 2-Nov-12 15:20pm
v2

1 solution

Try the code below:
C#
public class SendSms
{
    public SendSms(string number, string text)
    {
         string strNewValue;
         string strResponse;
 
         HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.buymessage.com/ostazSms/send.php");          
 
         req.Method = "POST";
         req.ContentType = "application/x-www-form-urlencoded";
         strNewValue = "usr=****&pwd=*****&to={0}&msg={1}"; 
         
         byte[] byteArray = Encoding.UTF8.GetBytes(string.Format(strNewValue,number, text));
         req.ContentLength = byteArray.Length;
         Stream dataStream = req.GetRequestStream();
         dataStream.Write(byteArray, 0, byteArray.Length);
         dataStream.Close();
         
         try
         {
                HttpWebResponse response = (HttpWebResponse)req.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader SR = new StreamReader(dataStream, Encoding.Unicode);
                strResponse = SR.ReadToEnd();
                response.Close();
                dataStream.Close();
                SR.Close();
                req.Abort();
         }
         catch {req.Abort();} 
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900