Jump to content
  • Advertisement
Sign in to follow this  
ThunderSoul

web forms and c#

This topic is 3832 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Say there is a web form on some site, with let's say fields "Name" and "Last Name" and when you click a button, say "Submit", your name and last names are sent to a database. What I want to do is write a C# application that will fill in those fields for me automatically with the names that I want and simulate pushing the "Submit" button... how would I do that? Thank you!

Share this post


Link to post
Share on other sites
Advertisement
You can use the aptly-named WebRequest class to make web requests.

The following demo code POSTs fields to rot13.com. The fields are stored in a Dictionary; the CreateQueryString method might be useful. [smile]

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace PostWebRequestDemo {
class Program {
static void Main(string[] args) {

// Here are the fields to submit.
var Fields = new Dictionary<string, string>();
Fields.Add("text", "P funec naq .ARG ner pbby, ab?" + Environment.NewLine + "Abgr ubj guvf vf pbeerpgyl HEY-rapbqrq.");
Fields.Add("other", "There is no other field, but let's pretend!");

// Create a WebRequest instance to perform the query.
var Request = WebRequest.Create("http://www.rot13.com/");
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";

// Turn fields into a query string.
var RequestParams = CreateQueryString(Fields);
Request.ContentLength = RequestParams.Length;

// Write our request.
using (var RequestStreamWriter = new StreamWriter(Request.GetRequestStream(), Encoding.Default)) {
RequestStreamWriter.Write(RequestParams);
}

// Execute/Read the response.
string Response = "";
using (var ResponseReader = new StreamReader(Request.GetResponse().GetResponseStream())) {
Response = ResponseReader.ReadToEnd();
}



}

private static string CreateQueryString(IEnumerable<KeyValuePair<string, string>> fields) {
var EncodedFields = new List<string>();
foreach (var Field in fields) {
EncodedFields.Add(HttpUtility.UrlEncode(Field.Key) + "=" + HttpUtility.UrlEncode(Field.Value));
}
return string.Join("&", EncodedFields.ToArray());
}

}
}

You will need to add a reference to System.Web to use the HttpUtility class.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!