DownloadString not getting executed
本文关键字:executed getting not DownloadString | 更新日期: 2023-09-27 17:59:41
我是C#的新手。网络编程面临的一个问题。当我调用getLocation函数时,我总是得到空的"location"。我知道我做事情的方式不对。但如果有人能帮助我以正确的方式去做,那就太好了。我希望getLocation函数返回位置值。因此,它应该只在返回位置值之前执行wc.downloadString时才返回。
public String getLocation()
{
RetrieveFormatedAddress(latitude, longitutde);
location = returnVal;
return location;
}
static void RetrieveFormatedAddress(string lat, string lng)
{
string requestUri = string.Format(baseUri, lat, lng);
using (WebClient wc = new WebClient())
{
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadString(new Uri(requestUri));
//wc.DownloadStringAsync(new Uri(requestUri));
}
}
private static void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var xmlElm = XElement.Parse(e.Result);
var status = (from elm in xmlElm.Descendants()
where elm.Name == "status"
select elm).FirstOrDefault();
if (status.Value.ToLower() == "ok")
{
var res = (from elm in xmlElm.Descendants()
where elm.Name == "formatted_address"
select elm).FirstOrDefault();
returnVal = res.Value;
}
else
{
returnVal = "No Address Found";
}
}
public String getLocation()
{
return RetrieveFormatedAddress(latitude, longitutde);
}
static string RetrieveFormatedAddress(string lat, string lng)
{
string requestUri = string.Format(baseUri, lat, lng);
using (WebClient wc = new WebClient())
{
var result = wc.DownloadString(new Uri(requestUri));
var xmlElm = XElement.Parse(result);
var status = (from elm in xmlElm.Descendants()
where elm.Name == "status"
select elm).FirstOrDefault();
if (status.Value.ToLower() == "ok")
{
var res = (from elm in xmlElm.Descendants()
where elm.Name == "formatted_address"
select elm).FirstOrDefault();
return res.Value;
}
else
{
return "No Address Found";
}
}
}
DownloadString()
方法是DownloadStringAsync()
方法的同步版本。它以字符串形式返回从服务器下载的数据。在您的代码中,您不会在任何地方读取此值。尝试var data = wc.DownloadString(new Uri(requestUri));
获取数据。