Metro应用程序:C#,从互联网上读取文本文件
本文关键字:读取 取文本 文件 互联网 应用程序 Metro | 更新日期: 2023-09-27 18:06:27
我想要的很简单,我想通过我的应用程序从我的网站上读取文本文件,我在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应用程序
您应该能够使用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);
}
}
var httpClient = new HttpClient();
var text = await httpClient.GetStringAsync(uri);
包装在异步方法中,当然