2

我想要的很简单,我想通过我的应用程序从我的网站读取文本文件,我设法在 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();

我认为问题出在 Metro 应用程序中未知的 WebClient 和 GetResponse ()

4

2 回答 2

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);
    }
 }
于 2013-03-29T20:37:03.530 回答
1
var httpClient = new HttpClient();
var text = await httpClient.GetStringAsync(uri);

当然包含在异步方法中

于 2013-03-29T20:28:47.543 回答