標籤:style blog http color 使用 io 檔案 資料
1.在Web中添加天氣服務引用地址
http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl
2.在Web中添加Wcf服務介面IWeatherService.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Runtime.Serialization; 5 using System.ServiceModel; 6 using System.Text; 7 8 namespace EasySL.Web.WCF 9 {10 // 注意: 使用“重構”菜單上的“重新命名”命令,可以同時更改代碼和設定檔中的介面名“IWeatherService”。11 [ServiceContract]12 public interface IWeatherService13 {14 [OperationContract]15 string[] GetCityWeather(string CityName);16 }17 }
3.在Web中實現服務介面
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Runtime.Serialization; 5 using System.ServiceModel; 6 using System.Text; 7 8 namespace EasySL.Web.WCF 9 {10 // 注意: 使用“重構”菜單上的“重新命名”命令,可以同時更改代碼、svc 和設定檔中的類名“WeatherService”。11 // 注意: 為了啟動 WCF 測試用戶端以測試此服務,請在方案總管中選擇 WeatherService.svc 或 WeatherService.svc.cs,然後開始調試。12 public class WeatherService : IWeatherService13 {14 public string[] GetCityWeather(string CityName)15 {16 ServiceRefWeather.WeatherWebServiceSoapClient client = new ServiceRefWeather.WeatherWebServiceSoapClient("WeatherWebServiceSoap");17 string[] cityNameWeather = client.getWeatherbyCityName(CityName);18 return cityNameWeather;19 }20 }21 }
4.在client添加自己建立的Wcf服務地址、調用服務介面
/// <summary> /// 通過wcf擷取天氣資料資訊 /// </summary> private void InitDataWeather() { try { ServiceReference1.WeatherServiceClient client = new ServiceReference1.WeatherServiceClient(); client.GetCityWeatherCompleted += (s, e) => { try { if (e.Error == null) { string[] cityWeather = new string[e.Result.Count]; 講e.Result結果顯示在頁面中就ok了,然後我們將e.Result進行資料格式處理,運用隔離儲存區 (Isolated Storage)講結果儲存起來 } else { lbltitle1.Content = e.Error.Message; } } catch (Exception ex) { lbltitle1.Content = ex.Message; } }; client.GetCityWeatherAsync("北京"); } catch (Exception ex) { //lbltitle1.Content = ex.Message; } }
5.將資料結果存放到本地(運用隔離儲存區 (Isolated Storage)技術)
1 private void WeatherWriterIsolatedStorageFile(string str) 2 { 3 IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); 4 if (isf.FileExists("Weather.txt")) 5 { 6 isf.DeleteFile("Weather.txt"); 7 } 8 using (Stream stream = isf.CreateFile("Weather.txt")) 9 {10 using (StreamWriter writer = new StreamWriter(stream))11 {12 writer.WriteLine(str);13 }14 }15 }
6.讀取存放的資料結果(隔離儲存區 (Isolated Storage))
private void ReaderWeatherIsolatedStorageFile() { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); if (isf.FileExists("AppConfig/Weather.txt")) { using (Stream stream = isf.OpenFile("Weather.txt", FileMode.Open)) { using (StreamReader reader = new StreamReader(stream)) { string[] line = reader.ReadToEnd().Split(‘|‘); } } isf.DeleteFile("Weather.txt"); } else { InitDataWeather(); } }