错误:流不支持并发IO读取或写入操作

时间:2013-01-01 08:26:43

标签: c# concurrency stream streamreader

我正尝试从我的C#网络应用程序登录网站,直接从应用程序发送电子邮件,而不是让用户亲自访问网站。

注意:我尝试登录的网站每次加载页面时都会更改id的{​​{1}},即使在同一会话期间也是如此。因此,我决定阅读页面来源,提取文本框的textboxes,然后在发布消息时使用id

id

应用程序到达此行时停止

public partial class sender : System.Web.UI.Page
{
    string userID, userPwd, recepsID, msgText, loginResponseString, sessionCode, queryCode;
    private HttpWebRequest initRequest, loginRequest, msgRequest;
    private HttpWebResponse initResponse, loginResponse;
    private Object lockObj = new Object();

    protected void Page_Load(object sender, EventArgs e)
    {
        userID = Request.QueryString["userNumber"];
        userPwd = Request.QueryString["userPwd"];
        recepsID = Request.QueryString["receps"];
        msgText = Request.QueryString["msgBody"];
        if (userID != null && userPwd != null && recepsID != null & msgText != null)
            doLoginAndSendMessage(userID, userPwd, recepsID, msgText);
        else
            Response.Write("Some values are missing");
    }

    public void doLoginAndSendMessage(string uid, string pwd, string recepIds, string msg)
    {
        try
        {
            doLogin(uid, pwd, recepIds, msg);
        }
        catch (Exception ex)
        {
            Response.Write("Sending Failed, Please Try Again");
        }
    }

    public void doLogin(string strUserId, string strPassword, string strIds, string strMessage)
    {
        try
        {
            initRequest = (HttpWebRequest)WebRequest.Create("http://www.somewebsite.com/login.aspx");
            initRequest.CookieContainer = new CookieContainer();
            initRequest.Timeout = 60000;
            StreamReader initSr = new StreamReader(initRequest.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
            initSr.ReadToEnd();
            initSr.Close();

            loginRequest = (HttpWebRequest)WebRequest.Create("http://www.somewebsite.com/login.aspx");
            loginRequest.CookieContainer = new CookieContainer();
            loginRequest.Timeout = 60000;
            StringBuilder loginString = new StringBuilder();
            loginString.Append("LoginUserId=" + strUserId + "&LoginPassword=" + strPassword + "&RememberMe=1&Login=Login");
            byte[] loginData = Encoding.ASCII.GetBytes(loginString.ToString());
            //to get any cookies from the initial response
            initResponse = (HttpWebResponse)initRequest.GetResponse();
            //setting cookies
            loginRequest.CookieContainer.Add(initResponse.Cookies);
            //Adding Headers
            loginRequest.Method = "POST";
            loginRequest.ContentType = "application/x-www-form-urlencoded";
            loginRequest.ContentLength = loginData.Length;
            Stream loginStream = loginRequest.GetRequestStream();
            loginStream.Write(loginData, 0, loginData.Length);
            loginStream.Close();

            //Reading the response
            StreamReader loginSr = new StreamReader(loginRequest.GetResponse().GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
            loginResponseString = loginSr.ReadToEnd();
            loginSr.Close();

            if (loginResponseString.Contains("inbox.aspx"))
            {
                //get session code
                sessionCode = loginResponseString.Substring(125, 5);
                //call the sendmessage method
                sendMessage(strIds, strMessage);

            }
            else
            {
                Response.Write("Login Failed: Check Username and password");
            }
        }
        catch (Exception ex)
        {
            Response.Write("Sending Failed, Please Try Again");
        }
    }

    public void sendMessage(string strIds, string strMsg)
    {
        try
        {
            string[] ids = strIds.Split(',');
            for (int i = 0; i < ids.Length; i++)
            {
                msgRequest = (HttpWebRequest)WebRequest.Create("http://www.somewebsite.com/writenew.aspx?sessionid=" + sessionCode);
                msgRequest.CookieContainer = new CookieContainer();
                msgRequest.Timeout = 1000000;
                msgRequest.ReadWriteTimeout = 1000000;
                msgRequest.SendChunked = true;
                //to get any cookies from the initial response
                loginResponse = (HttpWebResponse)loginRequest.GetResponse();
                //setting cookies
                msgRequest.CookieContainer.Add(loginResponse.Cookies);
                //Adding Headers
                msgRequest.Method = "POST";
                msgRequest.ContentType = "application/x-www-form-urlencoded";

                Stream msgStream = msgRequest.GetRequestStream();

                Stream respStream = msgRequest.GetResponse().GetResponseStream();

                StreamReader codeRead = new StreamReader(respStream, System.Text.Encoding.GetEncoding("utf-8"));
                string temp = codeRead.ReadToEnd();
                codeRead.Close();
                respStream.Close();
                txtResponse.Text = temp;

                try
                {
                    int starInd = temp.IndexOf("UserId_");
                    //int endInd = starInd + 15;
                    string holder = temp.Substring(starInd, 15);
                    int startInd = holder.IndexOf("_") + 1;
                    queryCode = holder.Substring(startInd, 5);
                    txtSubString.Text = queryCode;
                }
                catch (Exception ex)
                {
                    txtSubString.Text = "SOME ERROR";
                }

                lock (lockObj)
                {
                    StringBuilder msgString = new StringBuilder();
                    msgString.Append("sessionid=" + queryCode + "&GlobalKeyId=1&MessageLength=988&ReceiveId_"
                        + queryCode + "=" + ids[i] + "&Message_" + queryCode + "=" + strMsg
                        + "&SendNow_" + queryCode + "=Send Now");
                    byte[] msgData = Encoding.ASCII.GetBytes(msgString.ToString());
                    msgStream.Write(msgData, 0, msgData.Length);
                    msgStream.Close();
                }

                //Reading the response
                StreamReader msgSr = new StreamReader(respStream, System.Text.Encoding.GetEncoding("utf-8"));
                string msgResponseString = msgSr.ReadToEnd();
                msgSr.Close();
                sessionCode = msgResponseString.Substring(123, 5);
            }
            Response.Write("Message Sent Successfully");
        }
        catch (Exception ex)
        {
            Response.Write("Sending Failed, Please Try Again<br/>" + ex.Message);
        }
    }
}

请帮我解决错误。谢谢

1 个答案:

答案 0 :(得分:3)

当你致电GetResponse()时,它将导致发送到目前为止建立的请求,并且客户端将获取响应。

您需要在致电GetResponse()之前构建完整的请求,否则您的请求将无法完成。在调用GetResponse()之后获取请求流并写入POST数据将抛出此异常,以表明在已经发送请求之后继续构建请求是没有意义的。