I am having trouble getting my code to work. I need to access a website that only has one line of text on it, and display it within a cmd prompt. The website is password protected so I am using webClient to store cookies and am trying to figure out how give it the username and password. The "using" statement isn't working, does anyone know what I could try instead?
using System;
using System.Net;
namespace Temperature
{
public class CookieAwareWebClient : WebClient
{
public CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
using (var client = new CookieAwareWebClient());
var values = new NameValueCollection
{
{"username", "admin"},
{"password","secret"},
};
client.UpLoadValues("http://10.10.1.52:8001/get?OID4.3.2.1=", values);
string tempString = client.DownloadString("http://10.10.1.52:8001/get?OID4.3.2.1=");
Stream response = myClient.OpenRead("http://10.10.1.52:8001/get?OID4.3.2.1=");
Console.WriteLine(tempString);
}
}
You're not using the using
block correctly. This:
using (var client = new CookieAwareWebClient());
Is basically the same as this:
using (var client = new CookieAwareWebClient())
{
}
You create the variable, but then don't do anything with it in the code block. So it falls out of scope immediately.
Move your code into that code block to use the variable you created:
using (var client = new CookieAwareWebClient())
{
var values = new NameValueCollection
{
{"username", "admin"},
{"password","secret"},
};
client.UpLoadValues("http://10.10.1.52:8001/get?OID4.3.2.1=", values);
string tempString = client.DownloadString("http://10.10.1.52:8001/get?OID4.3.2.1=");
// etc.
}
As an aside to understand what the using
block really does, it's logically equivalent to this:
try
{
var client = new CookieAwareWebClient();
// any code you add to the block
}
finally
{
client.Dispose();
}
So like any try
block, any code which makes use of a variable declared within that block would also need to be within that block.