我正在爲windows phone 7構建一個應用程序,我需要從Web服務提取數據並將其顯示在我的應用程序中。現在每次調用Web服務數據的頁面都會被稱爲Web服務,並且一次又一次地調用Web服務,因此需要花費時間來顯示數據。因此,我想將數據存儲在獨立存儲中,以便每次都不會調用Web服務。請幫助我做到這一點。我的代碼調用Web服務的地址是:將從Web服務接收的數據存儲在windows phone 7應用程序的隔離存儲中
public const string aboutxml = "about.xml";
public about()
{
InitializeComponent();
LoadData();
}
private void LoadData()
{
bool isSuccess;
//try to load data from iso store
var doc = ReadXml(out isSuccess);
if (isSuccess) PopulateList(doc);
//if failed (data doesn't exists in iso store), download data from web service
else
{
KejriwalService.aapSoapClient myclient = new KejriwalService.aapSoapClient();
myclient.getarvindAboutCompleted += new EventHandler<KejriwalService.getarvindAboutCompletedEventArgs>(myclient_getarvindAboutCompleted);
myclient.getarvindAboutAsync();
progressName.Visibility = System.Windows.Visibility.Visible;
}
}
//upon download completed, display data then save the xml to iso store
void myclient_getarvindAboutCompleted(object sender, KejriwalService.getarvindAboutCompletedEventArgs e)
{
var doc = XDocument.Parse(e.Result);
PopulateList(doc);
WriteXml(doc);
}
private void PopulateList(XDocument doc)
{
var data = e.Result;
XElement xml = XElement.Parse(data);
aboutview.Text = xml.Elements("UserDetails").Elements("about_details").First().Value;
progressName.Visibility = System.Windows.Visibility.Collapsed;
}
private XDocument ReadXml(out bool isSuccess)
{
isSuccess = false;
var doc = new XDocument();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
if (store.FileExists(aboutxml))
{
using (var sr = new StreamReader(new IsolatedStorageFileStream(aboutxml, FileMode.OpenOrCreate, store)))
{
doc = XDocument.Load(sr);
}
isSuccess = true;
}
}
catch (Exception ex) { }
}
return doc;
}
private bool WriteXml(XDocument document)
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
using (var sw = new StreamWriter(new IsolatedStorageFileStream(aboutxml, FileMode.Create, store)))
{
sw.Write(document.ToString());
}
}
catch (Exception ex) { return false; }
}
return true;
}
有一個小錯誤。錯誤是:名稱SaveXml在當前上下文中不存在 – bhaku
ok,更改爲WriteXml。 – har07
非常感謝......現在它工作得很好。 – bhaku