我昨天运行了一个控制台应用程序来发送和接收Web请求和Web响应,它运行正常。今天我在我的表单应用程序上测试相同的方法,我得到错误WebRequest不包含创建定义。我所有的进口都是一样的。这有点奇怪,我不知道我做错了什么。这是我的控制台应用程序的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.Net;
using System.IO;
namespace WebrequestCsharp
{
class Program
{
static void Main(string[] args)
{
StreamWriter sw;
sw = File.AppendText("c:\\Temp\\webresponse.txt");
//Create a Web-Request to an URL
HttpWebRequest HWR_Request = (HttpWebRequest)WebRequest.Create("http://www.hitta.se/ericsson/företag_och_personer");
//Send Web-Request and receive a Web-Response
HttpWebResponse HWR_Response = (HttpWebResponse)HWR_Request.GetResponse();
//Translate data from the Web-Response to a string
Stream S_DataStream = HWR_Response.GetResponseStream();
StreamReader SR_DataStream = new StreamReader(S_DataStream, Encoding.UTF8);
string s_ResponseString = SR_DataStream.ReadToEnd();
S_DataStream.Close();
sw.WriteLine(s_ResponseString);
sw.Flush();
sw.Close();
HtmlDocument doc = new HtmlDocument();
doc.Load("c:\\Temp\\webresponse.txt");
Console.ReadKey();
}
}
}
这是我的表单应用程序无法接受我的创建:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.Net;
using System.IO;
namespace PhoneFind
{
class WebRequest
{
private String url { get; set; }
private String searchEngine { get; set; }
HttpWebRequest HWR_Request = (HttpWebRequest)WebRequest.Create("http://www.hitta.se/ericsson/företag_och_personer");
public WebRequest(String url, String searchEngine)
{
this.url = url;
this.searchEngine = searchEngine;
}
// sends a request to the search engine
public String sendRequest(String url, String searchEngine)
{
switch (searchEngine){
case "hitta":
//Create a Web-Request to a URL
//Send Web-Request and receive a Web-Response
HttpWebResponse HWR_Response = (HttpWebResponse)HWR_Request.GetResponse();
//Translate data from the Web-Response to a string
Stream S_DataStream = HWR_Response.GetResponseStream();
StreamReader SR_DataStream = new StreamReader(S_DataStream, Encoding.UTF8);
string s_ResponseString = SR_DataStream.ReadToEnd();
S_DataStream.Close();
break;
}
return "";
}
}
}
答案 0 :(得分:3)
在表单应用程序中,您的类名为WebRequest
,因此编译器正在该类中查找Create
方法,而不是System.Net.WebRequest
类。要解决此问题,请完全限定System.Net中的WebRequest
:
HttpWebRequest HWR_Request = (HttpWebRequest)System.Net.WebRequest.Create("http://www.hitta.se/ericsson/företag_och_personer");
感谢Amiram澄清这不是一个模糊的名称冲突,正如我原先认为的那样。
答案 1 :(得分:0)
出现此问题是因为您定位.net framework
小于4.5
,要解决此问题,只需将target framework
更改为4.5
,然后再project properties application tab
,然后重建项目。