【问题标题】:Metro Apps: C#, read text file from internetMetro Apps:C#,从互联网读取文本文件
【发布时间】:2013-03-29 20:16:02
【问题描述】:

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

【问题讨论】:

  • 为什么不WebClient.DownloadString(url)
  • 找不到类型或命名空间名称“WebClient”,我认为 WebClient 类不在 Metro-ui 应用程序中
  • 好的,谢谢,我会看到的

标签: c# microsoft-metro windows-store-apps


【解决方案1】:

您应该能够使用 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);
    }
 }

【讨论】:

  • 我尝试使用 localhost 地址,我得到这个“提供了无效的请求 URI。请求 URI 必须是绝对 URI 或必须设置 BaseAddress。”
【解决方案2】:
var httpClient = new HttpClient();
var text = await httpClient.GetStringAsync(uri);

当然是在异步方法中结束

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    相关资源
    最近更新 更多