简体   繁体   中英

C# HttpWebRequest & HttpWebResponse

I have a question/I need help, I'm trying to make a "updater" for my C# program, and I'm always getting this error

Cannot implicitly convert type 'System.Net.WebRequest' to 'System.Net.HttpWebRequest'. An explicit conversion exists (are you missing a cast?)

I was trying to make this "updater" as similar as possible to my .vb "updater", if anyone could help me solve this error I would be very thankful and happy, or if someone can send me a link to read about C# etc. I would also be very thankful, I'm very new to C# or the C family as well

System.Net.HttpWebRequest request = System.Net.HttpWebRequest.Create("link");
System.Net.HttpWebResponse response = request.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
string newestversion = sr.ReadToEnd();
string currentversion = Application.ProductVersion;

Thanks in advance!

You have to use the System.Net.WebRequest.Create method and cast the returned instance to System.Net.HttpWebRequest :

HttpWebRequest myReq =
    (HttpWebRequest)WebRequest.Create("http://www.contoso.com/");

See: https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=vs.110).aspx#Anchor_7

HttpWebRequest.Create() is actually WebRequest.Create() , which returns a WebRequest . You can cast it to HttpWebRequest if needed.

If you look at documentation for WebRequest.Create you will see that return type of the method is WebRequest , so you need to return it in your code:

System.Net.WebRequest request = System.Net.HttpWebRequest.Create("http://www.google.com");
System.Net.WebResponse response = request.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
string newestversion = sr.ReadToEnd();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM