views:

20

answers:

2

I am trying to retrieve a web page, add some text at the top of the page then I will be sending off the string. Here is a example framework of what I am trying to do. Is this the correct method or am I doing a big no-no somewhere?

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
var responce = (HttpWebResponse)request.GetResponse();
var responseStream = responce.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseString = reader.ReadToEnd();

StringBuilder sb = new StringBuilder(responseString);

var index = sb.ToString().IndexOf("<body>", StringComparison.InvariantCultureIgnoreCase)+"<body>".Length;
sb.Insert(index, "A lot of text will go here.");
Console.WriteLine(sb.ToString());
A: 

At some point, you may want to call responce.Close() and reader.Close()

joelt
+1  A: 

Is there any particular reason you need to use HttpWebRequest/Response? You could alternatively use the WebClient class like this to achieve the same result:

WebClient web_client = new WebClient();
byte[] result = web_client.DownloadData("http://blah...");
string html = System.Text.Encoding.Default.GetString(result);
html.IndexOf("<body>") ...

Little bit less code like that as well.

codykrieger
Or even web_client.DownloadString()
Jesper Palm
Yeah, that would work as well!
codykrieger
WebClient was the exact thing I was looking for. Thanks.
Scott Chamberlain
Sure thing, glad I was able to help you out!
codykrieger