Hi All.
I'm hoping somebody could help me out with this little problem I'm having, I've been at it for 8+ hours so far and just can't nail it.
The 2 blocks of code below I'm using to log into a fresh install of phpbb forums, and they work just fine.
The problem lies somewhere in the third block. (this one is just going back to the main page)
It doesn't pick up the cookies from the container.

private void forum_Login()
        {
            CookieContainer boardCookies = login("http://127.0.0.1/phpBB3/ucp.php?mode=login", this.login_user.Text, this.login_pass.Text);
            if (boardCookies != null)
            {
               MessageBox.Show("Logged in succeeded");
            }
            else
            {
             MessageBox.Show("Logged in Failed");
            }
public static CookieContainer login(string url, string username, string password)
        {
            if (url.Length == 0 || username.Length == 0 || password.Length == 0)
            {
                MessageBox.Show("Login Information missing");
                return null;
            }

            CookieContainer myContainer = new CookieContainer();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = new CookieContainer();

            // Set type to POST
            request.Method = "POST";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
            request.ContentType = "application/x-www-form-urlencoded";
            request.AllowAutoRedirect = false;
            // Build the new header, this isn't a multipart/form, so it's very simple
            StringBuilder data = new StringBuilder();
            data.Append("username=" + Uri.EscapeDataString(username));
            data.Append("&password=" + Uri.EscapeDataString(password));
            data.Append("&login=Login");
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

            // Set the content length in the request headers
            request.ContentLength = byteData.Length;

            Stream postStream;
            try
            {
                postStream = request.GetRequestStream();
            }
            catch (Exception e)
            {
                MessageBox.Show("Login - " + e.Message.ToString());
                return null;
            }

            // Write data
            postStream.Write(byteData, 0, byteData.Length);

            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (Exception e)
            {
                MessageBox.Show("Login - " + e.Message.ToString());
                return null;
            }

            bool isLoggedIn = false;
            // Store the cookies
            foreach (Cookie c in response.Cookies)
            {

                Console.WriteLine("Cookie:");
                Console.WriteLine("{0} = {1}", c.Name, c.Value);
                Console.WriteLine("Domain: {0}", c.Domain);
                Console.WriteLine("Path: {0}", c.Path);
                Console.WriteLine("Port: {0}", c.Port);
                Console.WriteLine("Secure: {0}", c.Secure);

                Console.WriteLine("When issued: {0}", c.TimeStamp);
                Console.WriteLine("Expires: {0} (expired? {1})",
                    c.Expires, c.Expired);
                Console.WriteLine("Don't save: {0}", c.Discard);
                Console.WriteLine("Comment: {0}", c.Comment);
                Console.WriteLine("Uri for comments: {0}", c.CommentUri);
                Console.WriteLine("Version: RFC {0}", c.Version == 1 ? "2109" : "2965");

                // Show the string representation of the cookie.
                Console.WriteLine("String: {0}", c.ToString());
                if (c.Name.Contains("_u"))
                {
                    if (Convert.ToInt32(c.Value) > 1)
                    {
                        isLoggedIn = true;
                    }
                }
                myContainer.Add(c);
               
            }

            if (isLoggedIn)
            {
                return myContainer;
            }
            else
            {
                return null;
            }
        }

Now, this next bit is where I'm having the problems. I'm expecting the forum to accept the cookies I grabbed from when the above code logged in.. but it's not doing it, and just sees the "visit" as somebody not logged in.

private void button8_Click(object sender, EventArgs e)
        {

            CookieContainer boardCookies = new CookieContainer();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://127.0.0.1/phpBB3");
            request.AllowAutoRedirect = true;
            request.CookieContainer = boardCookies;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                foreach (Cookie cookie in response.Cookies)
                {
                    MessageBox.Show("name " + cookie.Name);
                    MessageBox.Show("value " + cookie.Value.ToString() );
                }
            }

Can anybody see where I'm going wrong??

Use Wireshark to sniff the connection. Usually these forums execute client side code (javascript) to store another cookie. The HttpWebRequest is not javascript aware so the login never fully processes.

I have given similar code examples although perhaps not for phpbb, or this version of phpbb. If you can find a site online you want to automate the login to I could help.

Refer to:
Trying to Login to a Forum via C# Winforms application using HttpWebRequest
Help with HttpWebRequest

Thanks for the reply Sknake..
I managed to get it working using some different code. So now just need clean it all up a bit.

CookieContainer cookieContainer = new CookieContainer();

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //*********** need error checking for no connection
            Uri uri = new Uri("http://127.0.0.1/phpBB3/ucp.php?mode=login");

            string data = "username=test";
            data += "&password=825170";
            data += "&login=Login";
            if (uri.Scheme == Uri.UriSchemeHttp)
            {
                HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
                request.CookieContainer = cookieContainer;
                request.Method = WebRequestMethods.Http.Post;
                request.ContentLength = data.Length;
                request.ContentType = "application/x-www-form-urlencoded";
                StreamWriter writer = new StreamWriter(request.GetRequestStream());
                writer.Write(data);
                writer.Close();
                request.GetResponse();

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string tmp = reader.ReadToEnd();
                textBox1.Text = tmp;
                response.Close();
                if (tmp.IndexOf("maximum allowed number of login attempts.") > 0)
                {
                    MessageBox.Show("You have exceeded the maximum allowed number of login attempts.");
                    return;
                }
              
                if (tmp.IndexOf("Logout") > 0)
                {
                    foreach (Cookie c in response.Cookies)
                    {
                        if (c.Name.ToString() == "phpbb3_gk7dh_sid")
                        {
                            // get the session id 
                            string sid = c.Value.ToString();
                        }

                        //Because we're so paranoid, and don't trust the "logout" string check. Lets check the cookie to see if 
                        // it doesn't have the value of '1' (anonymous)
                        if (c.Name.ToString() == "phpbb3_gk7dh_u" && c.Value != "1")
                        {
                            label1.Text = "Logged in!!";
                           test(cookieContainer, uri);
                           return;
                        }
                        else
                        {
                            label1.Text = "Login Failed.";
                        }
                    }
                }
                         }
        }

// this is the second request, using the cookies grabbed from above
        private void test(CookieContainer cookieContainer, Uri uri)
        {
            uri = new Uri("http://127.0.0.1/phpBB3/test.php");
            if (uri.Scheme == Uri.UriSchemeHttp)
            {
                HttpWebRequest reques = HttpWebRequest.Create(uri) as HttpWebRequest;
                reques.CookieContainer = cookieContainer;
                reques.Method = WebRequestMethods.Http.Get;
                reques.ContentType = "application/x-www-form-urlencoded";
                HttpWebResponse response = reques.GetResponse() as HttpWebResponse;
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string tmp = reader.ReadToEnd();
                textBox1.Text = tmp; // throw the response into a textbox just for now.
                           }
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.