昨天我運行了一個控制檯應用程序來發送和接收Web請求和Web響應,它工作正常。今天我在我的表單應用程序上測試同樣的方法,並且得到錯誤WebRequest不包含創建定義。我所有的進口都是一樣的。這有點奇怪,我不知道我做錯了什麼。這是代碼到我的控制檯應用程序: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 "";
}
}
}
你想在一個名爲WebRequest的類中使用System.Net.WebRequest - 我很驚訝編譯器沒有抱怨模糊的名字。在你的表單程序中,嘗試'HttpWebRequest HWR_Request =(HttpWebRequest)System.Net.WebRequest.Create(「http://www.hitta.se/ericsson/foretag_och_personer」);' – Tim
@Tim,優先級,因爲代碼在這個類中。 –
@AmiramKorach - 謝謝。不確定是否會有歧義。但是這仍然解釋了他的錯誤,因爲他的類沒有包含「Create」的定義。 – Tim