我想要的很简单,我想通过我的应用程序从我的网站上读取文本文件,我设法在C#中执行此操作,但在Metro应用程序中没有这样做,这里我的代码在C#中
WebClient client = new WebClient();
Stream stream = client.OpenRead(strURL);
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
return content;
除了上面的代码我还尝试了下面的代码,但仍然失败
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(strURL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
byte[] buf = new byte[1000];
StringBuilder sb = new StringBuilder();
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.Unicode.GetString(buf, 0, count);
sb.Append(tempString);
}
}
return sb.ToString();
我认为问题出在WebClient和GetResponse()中,这在Metro应用程序中是未知的
答案 0 :(得分:2)
您应该可以使用System.Net.Http.HttpClient和HttpResponseMessage,因为它们包含在http://msdn.microsoft.com/en-us/library/windows/apps/hh454046.aspx中。
http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx上有一个例子:
static async void Main()
{
try
{
// Create a New HttpClient object.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
// Above three lines can be replaced with new helper method in following line
// string body = await client.GetStringAsync(uri);
Console.WriteLine(responseBody);
}
catch(HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ",e.Message);
}
}
答案 1 :(得分:1)
var httpClient = new HttpClient();
var text = await httpClient.GetStringAsync(uri);
当然是以异步方式包装