private void MenuItem_Click(object sender, RoutedEventArgs e) { MenuItem menu = sender as MenuItem; string strTemp = menu.Tag.ToString(); using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { try { IsolatedStorageFileStream location; location = new IsolatedStorageFileStream("favoriteRoutes.dat", System.IO.FileMode.Open, storage); StreamReader sr = new StreamReader(location); string content = sr.ReadToEnd(); sr.Close(); location.Dispose(); content = content.Replace(strTemp, ""); location = new IsolatedStorageFileStream("favoriteRoutes.dat", System.IO.FileMode.Truncate, storage); StreamWriter sw = new StreamWriter(location); sw.Write(content); sw.Close(); location.Dispose(); } catch (Exception e1) { Debug.WriteLine(e1.Message); } } llsFavRoutes.ItemsSource = null; BindData(); }
// this code is modfied code from the following tutorial // http://blogs.msdn.com/b/mingfeis_code_block/archive/2010/10/03/windows-phone-7-how-to-store-data-and-pass-data-between-pages.aspx public void LoadClues() { EnterClues(); string elementNumber; using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { for (int i=0; i < noClues; i++) { elementNumber = "number"+clueId[i].ToString(); XDocument _doc = new XDocument(); XElement _clue = new XElement(elementNumber); XAttribute _clueId = new XAttribute("clueId", clueId[i]); XAttribute _clueText = new XAttribute("clueText", clueText[i]); XAttribute _barcodeRef = new XAttribute("barcodeRef", barcodeRef[i]); XAttribute _location = new XAttribute("location", location[i]); XAttribute _locInfo = new XAttribute("locInfo", locInfo[i]); XAttribute _latitude = new XAttribute("latitude", latitude[i]); XAttribute _longitude = new XAttribute("longitude", longitude[i]); _clue.Add(_clueId, _clueText, _barcodeRef, _location, _locInfo, _latitude, _longitude); _doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), _clue); IsolatedStorageFileStream memory = new IsolatedStorageFileStream(elementNumber + ".clue", System.IO.FileMode.Create, storage); System.IO.StreamWriter file = new System.IO.StreamWriter(memory); _doc.Save(file); file.Dispose(); memory.Dispose(); } } }
private void BindData() { using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { try { ObservableCollection<Route> routes = new ObservableCollection<Route>(); IsolatedStorageFileStream location = new IsolatedStorageFileStream("favoriteRoutes.dat", System.IO.FileMode.Open, storage); StreamReader sr = new StreamReader(location); string content = sr.ReadToEnd(); string[] strRoutes = content.Split(';'); foreach(string strTempRoute in strRoutes) { Route route = new Route(); string[] strRoute = strTempRoute.Split(','); if(strRoute[0] == WebService.GetCity()) { route.StartStat = strRoute[1]; route.EndStat = strRoute[2]; route.Info = strTempRoute + ";"; routes.Add(route); } } llsFavRoutes.ItemsSource = routes; location.Dispose(); } catch (Exception e1) { Debug.WriteLine(e1.Message); } } }
public static T LoadFromFile(string fileName) { System.IO.IsolatedStorage.IsolatedStorageFile isoFile = null; System.IO.IsolatedStorage.IsolatedStorageFileStream isoStream = null; System.IO.StreamReader sr = null; try { isoFile = IsolatedStorageFile.GetUserStoreForApplication(); isoStream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(fileName, FileMode.Open, isoFile); sr = new System.IO.StreamReader(isoStream); string xmlString = sr.ReadToEnd(); isoStream.Close(); sr.Close(); return(Deserialize(xmlString)); } finally { if ((isoFile != null)) { isoFile.Dispose(); } if ((isoStream != null)) { isoStream.Dispose(); } if ((sr != null)) { sr.Dispose(); } } }
public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; System.IO.IsolatedStorage.IsolatedStorageFile isoFile = null; System.IO.IsolatedStorage.IsolatedStorageFileStream isoStream = null; try { isoFile = IsolatedStorageFile.GetUserStoreForApplication(); isoStream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(fileName, FileMode.Create, isoFile); streamWriter = new System.IO.StreamWriter(isoStream); string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); isoStream.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } if ((isoFile != null)) { isoFile.Dispose(); } if ((isoStream != null)) { isoStream.Dispose(); } } }
/// <summary> /// 读取本地文件信息,SilverLight缓存中 /// </summary> /// <param name="rFileName">存储文件名</param> /// <returns>返回文件数据</returns> public static byte[] ReadSlByteFile(string rFileName) { System.IO.IsolatedStorage.IsolatedStorageFile isf = null; System.IO.Stream stream = null; byte[] buffer = null; try { isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); if (!isf.FileExists(rFileName)) { return(null); } stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, isf); buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); } finally { if (stream != null) { stream.Close(); // Close the stream stream.Dispose(); } isf.Dispose(); } return(buffer); }
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication(); if (!storage.FileExists("LeaveSettings.xml")) { this.PayPeriodBase.Text = PayPeriodUtilities.GetCurrentPayPeriod().AddDays(-1).ToShortDateString(); this.AnnualBalance.Focus(); } else { using (storage) { XElement _xml; IsolatedStorageFileStream location = new IsolatedStorageFileStream(@"LeaveSettings.xml", System.IO.FileMode.Open, storage); System.IO.StreamReader file = new System.IO.StreamReader(location); _xml = XElement.Parse(file.ReadToEnd()); if (_xml.Name.LocalName != null) { this.AnnualBalance.Text = _xml.Attribute("AnnualBalance").Value; this.SickBalance.Text = _xml.Attribute("SickBalance").Value; this.AnnualAccrue.Text = _xml.Attribute("AnnualAccrue").Value; this.SickAccrue.Text = _xml.Attribute("SickAccrue").Value; this.PayPeriodBase.Text = _xml.Attribute("PayPeriod").Value; } file.Dispose(); location.Dispose(); } } }
private void CopyFromContentToStorage(IsolatedStorageFile ISF, String SourceFile, String DestinationFile) { Stream Stream = Application.GetResourceStream(new Uri(SourceFile, UriKind.Relative)).Stream; IsolatedStorageFileStream ISFS = new IsolatedStorageFileStream(DestinationFile, System.IO.FileMode.Create, System.IO.FileAccess.Write, ISF); CopyStream(Stream, ISFS); ISFS.Flush(); ISFS.Close(); Stream.Close(); ISFS.Dispose(); }
public Questions() { IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication(); questions = new List<String>(); answeres = new List<Boolean>(); if (ISF.FileExists("Questions.xml")) { IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("Questions.xml", FileMode.Open, FileAccess.Read, FileShare.Read, ISF); var qslist = from c in XElement.Load(isoStream).Element("Questions").Elements() // Important we are loading from ISF updated from dropbox !! select c; ISF.Dispose(); isoStream.Dispose(); foreach (var el in qslist) { this.questions.Add(el.Value); if ((string)el.Attribute("answ") == "true") this.answeres.Add(true); else this.answeres.Add(false); } } else { ISF.Dispose(); var qslist = from c in XElement.Load("Assets/Questions.xml").Element("Questions").Elements() select c; foreach (var el in qslist) { this.questions.Add(el.Value); if ((string)el.Attribute("answ") == "true") this.answeres.Add(true); else this.answeres.Add(false); } } }
void ws_GetThongBaoDonCompleted(object sender, GetThongBaoDonCompletedEventArgs e) { if (e.Result != "") { //Load thong bao len RichEidit IsolatedStorageFileStream fs = new IsolatedStorageFileStream("Temp.doc", FileMode.OpenOrCreate, FileAccess.ReadWrite, str); BinaryWriter br = new BinaryWriter(fs); br.Write(Convert.FromBase64String(e.Result)); richEdit.LoadDocument(fs, DocumentFormat.Doc); this.Title = tieude; fs.Close(); fs.Dispose(); } else { richEdit.Text = "Nội dung thông báo trống"; } }
private void Open_Click(object sender, RoutedEventArgs e) { if (Files.SelectedItem != null) { app.Filename = (string)Files.SelectedItem; using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { IsolatedStorageFileStream location = new IsolatedStorageFileStream(app.Filename, System.IO.FileMode.Open, storage); System.IO.StreamReader file = new System.IO.StreamReader(location); app.Content = file.ReadToEnd(); file.Dispose(); location.Dispose(); } NavigationService.GoBack(); } }
public static Collection<LeaveEntry> GetCurrentLeaveEntries() { IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication(); if (storage.FileExists("LeaveRecords.xml")) { IsolatedStorageFileStream location = new IsolatedStorageFileStream("LeaveRecords.xml", System.IO.FileMode.Open, storage); System.IO.StreamReader file = new System.IO.StreamReader(location); XmlSerializer serializer = new XmlSerializer(typeof(Collection<LeaveEntry>)); Collection<LeaveEntry> entries = (Collection<LeaveEntry>)serializer.Deserialize(file); file.Dispose(); location.Dispose(); return entries; } else { return new Collection<LeaveEntry>(); } }
private void decode(object sender, RoutedEventArgs e) { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); LibmadWrapper Libmad = new LibmadWrapper(); IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(Mp3bytes, 0, Mp3bytes.Length); PCMStream = isf.CreateFile("decoded_pcm.pcm"); bool init = Libmad.DecodeMp32Pcm_Init(buffer); if (init) { List<short> samples = new List<short>(); RawPCMContent rpcc = null; try { while ((rpcc = Libmad.ReadSample()).count != 0) { short[] shortBytes = rpcc.PCMData.ToArray<short>(); byte[] rawbytes = new byte[shortBytes.Length * 2]; for (int i = 0; i < shortBytes.Length; i++) { rawbytes[2 * i] = (byte)shortBytes[i]; rawbytes[2 * i + 1] = (byte)(shortBytes[i] >> 8); } PCMStream.Write(rawbytes, 0, rawbytes.Length); } PCMStream.Flush(); PCMStream.Close(); PCMStream.Dispose(); MessageBox.Show("over"); Libmad.CloseFile(); } catch (Exception exception) { MessageBox.Show(exception.Message); } } isf.Dispose(); }
public void PorpAllSourcesToDb(ICollection<FeedSource> allFeedSources) { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { var stream = new IsolatedStorageFileStream("test.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write, store); try { FeedSourceCollection allSourcesCollection = new FeedSourceCollection(); allSourcesCollection.Items = new List<FeedSource>(allFeedSources); XmlSerializer serializer = new XmlSerializer(typeof(FeedSourceCollection)); serializer.Serialize(stream, allSourcesCollection); } finally { stream.Close(); stream.Dispose(); } } }
private void ApplicationBarIconButton_Click(object sender, EventArgs e) { System.IO.IsolatedStorage.IsolatedStorageFile storage = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); using (storage) { XDocument _doc = new XDocument(); XElement baseSetting = new XElement("BaseSetting"); XAttribute AnnualBalance = new XAttribute("AnnualBalance", this.AnnualBalance.Text); XAttribute SickBalance = new XAttribute("SickBalance", this.SickBalance.Text); XAttribute AnnualAccrue = new XAttribute("AnnualAccrue", this.AnnualAccrue.Text); XAttribute SickAccrue = new XAttribute("SickAccrue", this.SickAccrue.Text); XAttribute PayPeriod = new XAttribute("PayPeriod", this.PayPeriodBase.Text); baseSetting.Add(AnnualBalance, SickBalance, AnnualAccrue, SickAccrue, PayPeriod); _doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), baseSetting); IsolatedStorageFileStream location = new IsolatedStorageFileStream("LeaveSettings.xml", FileMode.Create, storage); StreamWriter file = new StreamWriter(location); _doc.Save(file); file.Dispose(); location.Dispose(); NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); } }
/// <summary> /// 保存信息至本地文件,SilverLight缓存中 /// </summary> /// <param name="rFileName"></param> /// <param name="buffer"></param> public static void WriteSlByteFile(string rFileName, byte[] buffer) { System.IO.IsolatedStorage.IsolatedStorageFile isf = null; System.IO.Stream stream = null; try { isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); if (rFileName.IndexOf(':') >= 0) { rFileName = rFileName.Substring(rFileName.LastIndexOf(':') + 1); } ClearSlFile(rFileName); string rPath = System.IO.Path.GetDirectoryName(rFileName); if (rPath != "") { isf.CreateDirectory(rPath); } stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.Write, isf); stream.Write(buffer, 0, buffer.Length); stream.Flush(); } finally { try { stream.Close(); // Close the stream too stream.Dispose(); isf.Dispose(); } catch { } } }
public static Basis GetBaseValues() { using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { Basis baseValues = new Basis(); XElement _xml; IsolatedStorageFileStream location = new IsolatedStorageFileStream(@"LeaveSettings.xml", System.IO.FileMode.Open, storage); System.IO.StreamReader file = new System.IO.StreamReader(location); _xml = XElement.Parse(file.ReadToEnd()); if (_xml.Name.LocalName != null) { baseValues.StartingAnnual = double.Parse(_xml.Attribute("AnnualBalance").Value); baseValues.StartingSick = double.Parse(_xml.Attribute("SickBalance").Value); baseValues.AnnualAccrue = double.Parse(_xml.Attribute("AnnualAccrue").Value); baseValues.SickAccrue = double.Parse(_xml.Attribute("SickAccrue").Value); baseValues.StartingPayPeriod = DateTime.Parse(_xml.Attribute("PayPeriod").Value); } file.Dispose(); location.Dispose(); return baseValues; } }
private void LoadDataFromStore() { IsolatedStorageFileStream isStream = null; try { lock (store) { isStream = new IsolatedStorageFileStream(storageAreaName + @"\" + itemsFileName, FileMode.Open, FileAccess.Read, FileShare.None, store); using (StreamReader reader = new StreamReader(isStream)) { if (!reader.EndOfStream) { items = (List<ItemModel>)serializer.Deserialize(reader); } } // this should implicitly dispose of isStream too } } catch (Exception) { } finally { if (items == null) items = new List<ItemModel>(); if (isStream != null) isStream.Dispose(); } }
public static void SaveLeave(LeaveEntry entry) { Collection<LeaveEntry> currentEntries = new Collection<LeaveEntry>(); IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication(); if (storage.FileExists("LeaveRecords.xml")) { currentEntries = GetCurrentLeaveEntries(); } currentEntries.Add(entry); IsolatedStorageFileStream location = new IsolatedStorageFileStream("LeaveRecords.xml", FileMode.OpenOrCreate, storage); XmlSerializer serializer = new XmlSerializer(typeof(Collection<LeaveEntry>)); StreamWriter file = new StreamWriter(location); serializer.Serialize(file, currentEntries); file.Dispose(); location.Dispose(); }
//public static CityTown getCityTown() //{ // DateTime startTime = DateTime.Now; // XmlReader reader = XmlReader.Create("Model/CityTownSp.xml"); // CityTown records = (CityTown)Utils.deserialize(reader, typeof(CityTown)); // DateTime stopTime = DateTime.Now; // System.Diagnostics.Debug.WriteLine("Elapsed: {0}", (stopTime - startTime).TotalMilliseconds); // return records; //} /* public static object deserialize(XmlReader reader, Type serializedObjectType) { if (serializedObjectType == null || reader == null) return null; XmlSerializer serializer = new XmlSerializer(serializedObjectType); return serializer.Deserialize(reader); }*/ public static void saveXML(string fileName, string content) { using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, FileAccess.Write, myIsolatedStorage)) { using (StreamWriter writer = new StreamWriter(isoStream)) { writer.Write(content, System.Text.Encoding.UTF8); writer.Flush(); writer.Close(); writer.Dispose(); } isoStream.Close(); isoStream.Dispose(); } } }
public void Create () { // Fails in Silverlight 3 IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication (); using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream ("moon", FileMode.Create, isf)) { Assert.IsTrue (fs.CanRead, "CanRead"); Assert.IsTrue (fs.CanSeek, "CanSeek"); Assert.IsTrue (fs.CanWrite, "CanWrite"); Assert.AreEqual (0, fs.Length, "Length"); Assert.AreEqual (0, fs.Position, "Position"); fs.Dispose (); Assert.IsFalse (fs.CanRead, "Dispose/CanRead"); Assert.IsFalse (fs.CanSeek, "Dispose/CanSeek"); Assert.IsFalse (fs.CanWrite, "Dispose/CanWrite"); Assert.Throws (delegate { Console.WriteLine (fs.Length); }, typeof (ObjectDisposedException), "Dispose/Length"); Assert.Throws (delegate { Console.WriteLine (fs.Position); }, typeof (ObjectDisposedException), "Dispose/Position"); fs.Dispose (); // multiple times (like using do to) isf.Remove (); Assert.Throws (delegate { new IsolatedStorageFileStream ("removed", FileMode.Create, isf); }, typeof (IsolatedStorageException), "Remove/new"); Assert.IsFalse (fs.CanRead, "Dispose/CanRead"); Assert.IsFalse (fs.CanSeek, "Dispose/CanSeek"); Assert.IsFalse (fs.CanWrite, "Dispose/CanWrite"); Assert.Throws (delegate { Console.WriteLine (fs.Length); }, typeof (IsolatedStorageException), "Dispose/Length"); Assert.Throws (delegate { Console.WriteLine (fs.Position); }, typeof (IsolatedStorageException), "Dispose/Position"); isf.Dispose (); Assert.Throws (delegate { new IsolatedStorageFileStream ("removed", FileMode.Create, isf); }, typeof (ObjectDisposedException), "Dispose/new"); Assert.IsFalse (fs.CanRead, "Dispose/CanRead"); Assert.IsFalse (fs.CanSeek, "Dispose/CanSeek"); Assert.IsFalse (fs.CanWrite, "Dispose/CanWrite"); Assert.Throws (delegate { Console.WriteLine (fs.Length); }, typeof (ObjectDisposedException), "Dispose/Length"); Assert.Throws (delegate { Console.WriteLine (fs.Position); }, typeof (ObjectDisposedException), "Dispose/Position"); } }
// 拨号完成 private void loginTh_RunWorkercompleted(object sender, RunWorkerCompletedEventArgs e) { custProgressBar.Hide(); string errorMessage=""; switch ((ClientHandleStatus)e.Result) { // 进行判断 case ClientHandleStatus.DrClient_Success: { // 拨号成功 bIsConnected = true; }break; case ClientHandleStatus.DrClient_AccountBreakOff: { errorMessage = AppResources.DrClient_AccountBreakOff; }break; case ClientHandleStatus.DrClient_AccountNotAllow: { errorMessage = AppResources.DrClient_AccountNotAllow; }break; case ClientHandleStatus.DrClient_AccountTieUp: { errorMessage = string.Format(AppResources.DrClient_AccountTieUp, _drClient.GetXip(), _drClient.GetMac()); }break; case ClientHandleStatus.DrClient_AlreadyOnline: { errorMessage = AppResources.DrClient_AlreadyOnline; }break; case ClientHandleStatus.DrClient_ChargeOrFluxOver: { errorMessage = AppResources.DrClient_ChargeOrFluxOver; }break; case ClientHandleStatus.DrClient_InvalidAccountOrPwd: { errorMessage = AppResources.DrClient_InvalidAccountOrPwd; }break; case ClientHandleStatus.DrClient_IpNotAllowLogin: { errorMessage = AppResources.DrClient_IpNotAllowLogin; }break; case ClientHandleStatus.DrClient_NetworkError: { errorMessage = AppResources.DrClient_NetworkError; }break; case ClientHandleStatus.DrClient_NewAndConfirmPwdDiffer: { errorMessage = AppResources.DrClient_NewAndConfirmPwdDiffer; }break; case ClientHandleStatus.DrClient_NotAllowChangePwd: { errorMessage = AppResources.DrClient_NotAllowChangePwd; }break; case ClientHandleStatus.DrClient_NotFoundDrCOM: { // 获取当前的网络SSID bool bIsWlanConnected = false; string CurrentSSID = GetCurrentSSID(ref bIsWlanConnected); errorMessage = string.Format(AppResources.DrClient_NotFoundDrCOM, CurrentSSID); }break; case ClientHandleStatus.DrClient_PwdAmendSuccessed: { errorMessage = AppResources.DrClient_PwdAmendSuccessed; }break; case ClientHandleStatus.DrClient_SystemBufferFull: { errorMessage = AppResources.DrClient_SystemBufferFull; }break; case ClientHandleStatus.DrClient_TieUpCannotAmend: { errorMessage = AppResources.DrClient_TieUpCannotAmend; }break; case ClientHandleStatus.DrClient_UndefineError: { errorMessage = AppResources.DrClient_UndefineError; }break; case ClientHandleStatus.DrClient_UsingAppointedMac: { errorMessage = string.Format(AppResources.DrClient_UsingAppointedMac, _drClient.GetMac()); }break; case ClientHandleStatus.DrClient_UsingNAT: { errorMessage = AppResources.DrClient_UsingNAT; }break; case ClientHandleStatus.DrClient_UsingOnAppointedIp: { errorMessage = string.Format(AppResources.DrClient_UsingOnAppointedIp, _drClient.GetXip()); }break; default: { errorMessage = AppResources.DrClient_UndefineError; }break; } if (bIsConnected == true) { // 保存最后一次正确登陆的网关,用户名和密码 settings.GatewayAddrSetting = _drClient.GetGatewayAddress(); settings.UsernameSetting = strUserName; settings.PasswordSetting = strPassWord; // 2013-6-2 Added by Sanwen settings.SavePasswordSetting = cbSavePassword.IsChecked.Value; settings.AutoLogindSetting = cbAutoLogin.IsChecked.Value; // 2013-8-28 Added by Sanwen // 将网关写入文件中 using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { if (storage.FileExists("settings")) { storage.DeleteFile("settings"); } try { XElement _item = new XElement("Settings"); _item.Add(new XElement("GatewayAddr", _drClient.GetGatewayAddress())); _item.Add(new XElement("schedulingCount", 0)); // 用_item 新建一个XML的Linq文档 XDocument _doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), _item); // 创建一个独立存储的文件流 IsolatedStorageFileStream location = new IsolatedStorageFileStream("settings", System.IO.FileMode.OpenOrCreate, FileAccess.ReadWrite, storage); // 将独立存储文件转化为可写流 System.IO.StreamWriter file = new System.IO.StreamWriter(location); // 将XML文件保存到流file上, 即可以写入到手机独立存储文件上 _doc.Save(file); file.Dispose(); // 关闭可写流 location.Dispose(); //关闭手机独立存储流 } catch (Exception ex) { string strerr = ex.Message; } } // ---End-tag--- btnLogin.Content = AppResources.btnLogout; btnLogin.Style = (Style)this.Resources["ButtonStyle2"]; // 禁止CheckBox cbAutoLogin.IsEnabled = false; cbSavePassword.IsEnabled = false; DynamicChangeLayout(); time_Tick(new object(), new EventArgs()); timerGetStatus.Start(); // 登录成功 GetUpdateInfo(); // 开启后台代理 StartPeriodicAgent(); } else { // 登录失败 btnLogin.Content = AppResources.btnLogin; // 提示用户失败原因 MessageBox.Show(errorMessage, "", MessageBoxButton.OK); } }
public bool Save(){ IsolatedStorageFile isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User| IsolatedStorageScope.Assembly|IsolatedStorageScope.Domain, typeof(System.Security.Policy.Url),typeof(System.Security.Policy.Url)); try { IsolatedStorageFileStream theStream; theStream = new IsolatedStorageFileStream(filename, FileMode.Create, isf); BinaryFormatter theFormatter = new BinaryFormatter(); theFormatter.Serialize(theStream, this); theStream.Dispose(); theStream.Close(); } catch (Exception e){ MessageBox.Show(e.Message,"Error"); return false; } return true; }
private void appBarBtnFav_Click(object sender, System.EventArgs e) { using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { try { IsolatedStorageFileStream location; if (!storage.FileExists("favoriteRoutes.dat")) { location = new IsolatedStorageFileStream("favoriteRoutes.dat", System.IO.FileMode.CreateNew, storage); location.Dispose(); } location = new IsolatedStorageFileStream("favoriteRoutes.dat", System.IO.FileMode.Open, storage); string strTemp = WebService.GetCity() + "," + m_strStart + "," + m_strEnd + ";"; StreamReader sr = new StreamReader(location); string content = sr.ReadToEnd(); sr.Close(); location.Dispose(); if (content.Contains(strTemp)) { MessageBox.Show("已收藏"); } else { location = new IsolatedStorageFileStream("favoriteRoutes.dat", System.IO.FileMode.Append, storage); StreamWriter sw = new StreamWriter(location); sw.Write(strTemp); sw.Close(); MessageBox.Show("收藏成功"); location.Dispose(); } } catch (Exception e1) { Debug.WriteLine(e1.Message); } } }
private void BindHistoryData() { using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { try { ObservableCollection<Route> routes = new ObservableCollection<Route>(); if (storage.FileExists("HistoryRoutes.dat")) { IsolatedStorageFileStream location = new IsolatedStorageFileStream("HistoryRoutes.dat", System.IO.FileMode.Open, storage); StreamReader sr = new StreamReader(location); string content = sr.ReadToEnd(); sr.Close(); string[] strRoutes = content.Split(';'); foreach (string strTempRoute in strRoutes) { Route route = new Route(); string[] strRoute = strTempRoute.Split(','); if (strRoute[0] == WebService.GetCity()) { route.StartStat = strRoute[1]; route.EndStat = strRoute[2]; route.Info = strRoute[1] + "-" + strRoute[2]; routes.Add(route); } } llsHistory.ItemsSource = routes; tbkHistory.Visibility = Visibility.Visible; btnClearHistory.Visibility = Visibility.Visible; llsHistory.Visibility = Visibility.Visible; location.Dispose(); } else { tbkHistory.Visibility = Visibility.Collapsed; btnClearHistory.Visibility = Visibility.Collapsed; llsHistory.Visibility = Visibility.Collapsed; } } catch (Exception e1) { Debug.WriteLine(e1.Message); } } }
void ad_NewAdAvailable(object sender, EventArgs e) { if (Ad.Status == "success" && Ad.AdImageFileName != null && Ad.ImageOK) { try { if (CurrentImageFile != Ad.AdImageFileName) { CurrentImageFile = Ad.AdImageFileName; IsolatedStorageFile myIsoStore = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream myAd = new IsolatedStorageFileStream(Ad.AdImageFileName, FileMode.Open, myIsoStore); Texture2D intr = Texture2D.FromStream((Atom.Shared.Globals.Engine as GameBase).GraphicsDevice, myAd); lock (this) { if(Texture!=null) Texture.Dispose(); Texture = intr; } myAd.Dispose(); myIsoStore.Dispose(); } } catch(Exception ex) { string s = ex.Message; } } }
/// <summary> /// 保存信息至本地文件,SilverLight缓存中 /// </summary> /// <param name="rFileName"></param> /// <param name="buffer"></param> public static void WriteSlByteFile(string rFileName, byte[] buffer) { System.IO.IsolatedStorage.IsolatedStorageFile isf = null; System.IO.Stream stream = null; try { isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); if (rFileName.IndexOf(':') >= 0) { rFileName = rFileName.Substring(rFileName.LastIndexOf(':') + 1); } ClearSlFile(rFileName); string rPath = System.IO.Path.GetDirectoryName(rFileName); if (rPath != "") { isf.CreateDirectory(rPath); } stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.Write, isf); stream.Write(buffer, 0, buffer.Length); stream.Flush(); } finally { try { stream.Close(); // Close the stream too stream.Dispose(); isf.Dispose(); } catch { } } }
} // StartVideoRecording() private void StopVideoRecording() { try { // Stop recording. if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Started) { captureSource.Stop(); // Disconnect fileSink. fileSink.CaptureSource = null; fileSink.IsolatedStorageFileName = null; // Set the button states and the message. UpdateUI(ButtonState.Stopped, "Recording stopped..."); viewfinderRectangle.Fill = null; // Create the file stream isoVideoFile = new IsolatedStorageFileStream(fileName, FileMode.Open, FileAccess.Read, IsolatedStorageFile.GetUserStoreForApplication()); MemoryStream videoStream = new MemoryStream(); using (isoVideoFile) { isoVideoFile.CopyTo(videoStream); } PurposeColor.screens.AddEventsSituationsOrThoughts.ReceiveVideoFromWindows(videoStream, isoVideoFile.Name); isoVideoFile.Flush(); isoVideoFile.Dispose(); isoVideoFile = null; //videoStream = null; DisposeVideoRecorder(); } } // If stop fails, display an error. catch (Exception e) { this.Dispatcher.BeginInvoke(delegate() { txtDebug.Text = "ERROR: " + e.Message.ToString(); }); } }//StopVideoRecording()
/// <summary> /// 保存数据 /// </summary> private void SaveData() { using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { XDocument _doc = new XDocument(); // root XElement _root = new XElement("Ido"); // today and future XElement _today = new XElement("Today"); AddItems(_today); _root.Add(_today); _doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), _root); IsolatedStorageFileStream location = new IsolatedStorageFileStream("Content.xml", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.Read, storage); System.IO.StreamWriter file = new System.IO.StreamWriter(location); _doc.Save(file); file.Dispose(); location.Dispose(); } }
public static RedmineDataBuffer Read(){ RedmineDataBuffer theReturn = null; try { IsolatedStorageFile isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User| IsolatedStorageScope.Assembly|IsolatedStorageScope.Domain, typeof(System.Security.Policy.Url),typeof(System.Security.Policy.Url)); IsolatedStorageFileStream theStream; theStream = new IsolatedStorageFileStream(filename, FileMode.Open, isf); BinaryFormatter theFormatter = new BinaryFormatter(); theReturn = (RedmineDataBuffer)theFormatter.Deserialize(theStream); theStream.Dispose(); theStream.Close(); } catch { return null; } //Backward compatibility: Some may use old save files and we need some initialized dataset: if (theReturn.projects == null) { theReturn.projects = new SortedDictionary<string,int>(); } if (theReturn.priorities == null) { theReturn.priorities = new SortedDictionary<string,int>(); } if (theReturn.trackers == null) { theReturn.trackers = new SortedDictionary<string,int>(); } if (theReturn.issues == null) { theReturn.issues = new SortedDictionary<int,RedmineIssueStorage>(); } if (theReturn.trackers == null) { theReturn.trackers = new SortedDictionary<string,int>(); } if (theReturn.currentIssues == null) { theReturn.currentIssues = new SortedDictionary<string,int>(); } if (theReturn.allIssues == null) { theReturn.allIssues = new SortedDictionary<string,int>(); } if (theReturn.statuses == null) { theReturn.statuses = new SortedDictionary<string,int>(); } return theReturn; }
public static void DownloadFileVerySimle(Uri fileAdress, string fileName) { System.Net.WebClient client = new System.Net.WebClient(); client.DownloadStringCompleted += (s, ev) => { IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication(); StreamWriter writeToFile = new StreamWriter(ISF.CreateFile(fileName)); try { writeToFile.Write(ev.Result); writeToFile.Dispose(); IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, ISF); string ver = XElement.Load(isoStream).Element("version").Value.Trim().ToString(); MessageBox.Show("Pobrano pomyślnie wersje "+ver+" bazy pytań !", "AKTUALIZACJA", MessageBoxButton.OK); isoStream.Dispose(); ISF.Dispose(); } catch (Exception) { MessageBox.Show("Wystąpił błąd ! Spróbuj ponownie i upewnij się że masz połączenie z siecią", "AKTUALIZACJA", MessageBoxButton.OK); writeToFile.Dispose(); if(ISF.FileExists(fileName)) ISF.DeleteFile(fileName); ISF.Dispose(); } }; client.DownloadStringAsync(fileAdress); }
/// <summary> /// 运行计划任务的代理 /// </summary> /// <param name="task"> /// 调用的任务 /// </param> /// <remarks> /// 调用定期或资源密集型任务时调用此方法 /// </remarks> protected override void OnInvoke(ScheduledTask task) { string strGateWay = ""; using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { XElement _xml; try { IsolatedStorageFileStream location = new IsolatedStorageFileStream("settings", System.IO.FileMode.Open, storage); // 转化为可读流 System.IO.StreamReader file = new System.IO.StreamReader(location); // 解析流转化为XML _xml = XElement.Parse(file.ReadToEnd()); strGateWay = _xml.Element("GatewayAddr").Value; schedulingCount = Convert.ToInt32(_xml.Element("schedulingCount").Value); file.Dispose(); // 关闭可写流 location.Dispose(); //关闭手机独立存储流 } catch (System.Exception ex) { } } //if (null==strGateWay || strGateWay.Length==0) //{ // return; //} _drClient.Init(); // 读取上一次正常登录的网关地址 string strGatewayAddr = strGateWay; if (schedulingCount % 2 == 0) { _drClient.SetGatewayAddress(strGatewayAddr); int nRet =_drClient.GetStatus(); if ( (ClientHandleStatus)nRet == ClientHandleStatus.DrClient_Success) { // 成功获取到状态,更新磁贴 string flux = _drClient.GetFluxStatus(); string time = _drClient.GetTimeStatus(); string updatetime = DateTime.Now.ToString("HH:mm"); UpdateTile(time, flux, updatetime); } else if ( (ClientHandleStatus)nRet == ClientHandleStatus.DrClient_NetworkError || (ClientHandleStatus)nRet == ClientHandleStatus.DrClient_UndefineError) { // 网络已经断开, 更新磁贴 UpdateTileState(); } } schedulingCount++; using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { if (storage.FileExists("settings")) { storage.DeleteFile("settings"); } try { XElement _item = new XElement("Settings"); _item.Add(new XElement("GatewayAddr", strGateWay)); _item.Add(new XElement("schedulingCount", schedulingCount)); // 用_item 新建一个XML的Linq文档 XDocument _doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), _item); // 创建一个独立存储的文件流 IsolatedStorageFileStream location = new IsolatedStorageFileStream("settings", System.IO.FileMode.OpenOrCreate, FileAccess.ReadWrite, storage); // 将独立存储文件转化为可写流 System.IO.StreamWriter file = new System.IO.StreamWriter(location); // 将XML文件保存到流file上, 即可以写入到手机独立存储文件上 _doc.Save(file); file.Dispose(); // 关闭可写流 location.Dispose(); //关闭手机独立存储流 } catch (Exception ex) { string strerr = ex.Message; } // XElement _xml; // try // { // IsolatedStorageFileStream location = new IsolatedStorageFileStream("settings", System.IO.FileMode.Open, FileAccess.ReadWrite, storage); // // StreamWriter filewrite = new StreamWriter(location); // StreamReader file = new StreamReader(location); // _xml = XElement.Parse(file.ReadToEnd() ); // file.Dispose(); // file.Close(); // location.Dispose(); // location.Close(); // IsolatedStorageFileStream location2 = new IsolatedStorageFileStream("settings", System.IO.FileMode.Open, FileAccess.ReadWrite, storage); // StreamWriter filewrite = new StreamWriter(location2); // _xml.Element("schedulingCount").SetValue(schedulingCount); // _xml.Save(filewrite); // filewrite.Flush(); // filewrite.Dispose(); // filewrite.Close(); //// // 转化为可读流 //// System.IO.StreamReader fileRead = new System.IO.StreamReader(location); //// // 解析流转化为XML //// _xml = XElement.Parse(fileRead.ReadToEnd()); //// _xml.Element("schedulingCount").SetValue(schedulingCount); //// fileRead.Dispose(); // 关闭可写流 //// // 将修改后的XML写入文件 //// // IsolatedStorageFileStream location2 = new IsolatedStorageFileStream("settings", System.IO.FileMode.Open, FileAccess.Write,storage); //// System.IO.StreamWriter fileWrite = new System.IO.StreamWriter(location); //// _xml.Save(fileWrite); //// fileWrite.Dispose(); //// location.Dispose(); // // location2.Dispose(); // } // catch (System.Exception ex) // { // Debug.WriteLine(ex.Message); // } } //TODO: 添加用于在后台执行任务的代码 // If debugging is enabled, launch the agent again in one minute. #if DEBUG_AGENT ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60)); #endif NotifyComplete(); }
/// <summary> /// 保存设置 /// </summary> /// <param name="firstrun"></param> private void SaveSettings(bool firstrun = false) { using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { XDocument _doc = new XDocument(); // root XElement _root = new XElement("Settings"); // general and livetiles XElement _general = new XElement("General"); XElement _livetiles = new XElement("LiveTiles"); // general items XElement _autoclean; // live tiles items XElement _flip; if (firstrun) { _autoclean = new XElement("AutoClean", "False"); _flip = new XElement("Flip", "False"); } else { _autoclean = new XElement("AutoClean", autoclean.ToString()); _flip = new XElement("Flip", flip.ToString()); } _general.Add(_autoclean/*, _theme*/); _livetiles.Add(_flip); _root.Add(_general, _livetiles); _doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), _root); IsolatedStorageFileStream location = new IsolatedStorageFileStream("Settings.xml", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.Read, storage); System.IO.StreamWriter file = new System.IO.StreamWriter(location); _doc.Save(file); file.Dispose(); location.Dispose(); } }
/// <summary> /// 读取本地文件信息,SilverLight缓存中 /// </summary> /// <param name="rFileName">存储文件名</param> /// <returns>返回文件数据</returns> public static byte[] ReadSlByteFile(string rFileName) { System.IO.IsolatedStorage.IsolatedStorageFile isf = null; System.IO.Stream stream = null; byte[] buffer = null; try { isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); if (!isf.FileExists(rFileName)) return null; stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read, isf); buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); } finally { if (stream != null) { stream.Close(); // Close the stream stream.Dispose(); } isf.Dispose(); } return buffer; }