Metro应用程序:C#,从internet读取文本文件
我想要的很简单,我想通过我的应用程序从我的网站上读取一个文本文件,我设法用C#实现了这一点,但在metro应用程序中没有,这里是我用C编写的代码# 除了上面的代码,我还尝试了下面的代码,但仍然失败Metro应用程序:C#,从internet读取文本文件,c#,microsoft-metro,windows-store-apps,C#,Microsoft Metro,Windows Store Apps,我想要的很简单,我想通过我的应用程序从我的网站上读取一个文本文件,我设法用C#实现了这一点,但在metro应用程序中没有,这里是我用C编写的代码# 除了上面的代码,我还尝试了下面的代码,但仍然失败 HttpWebRequest request = (HttpWebRequest) WebRequest.Create(strURL); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream resStr
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应用程序中是未知的
var httpClient = new HttpClient();
var text = await httpClient.GetStringAsync(uri);
当然,在异步方法中,您应该能够使用System.Net.Http.HttpClient和HttpResponseMessage,因为它们包含在中 例如:
为什么不
WebClient.DownloadString(url)
?找不到类型或命名空间名称“WebClient”,我认为WebClient类不在metro ui应用程序中可能重复确定,谢谢,我将看到它,我将使用localhost地址进行尝试,我明白了“提供了无效的请求URI。请求URI必须是绝对URI或必须设置基地址。“
var httpClient = new HttpClient();
var text = await httpClient.GetStringAsync(uri);
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);
}
}