public SlowkaClass() { slowka = new List<Slowko>(); XDocument doc = null; IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream storageStream = null; if(storage.FileExists("slowka.xml")) { storageStream = new IsolatedStorageFileStream("slowka.xml", System.IO.FileMode.Open, FileAccess.Read, storage); doc = XDocument.Load(storageStream); storageStream.Close(); } else { doc = XDocument.Load("slowka.xml"); storageStream = new IsolatedStorageFileStream("slowka.xml", System.IO.FileMode.CreateNew, FileAccess.Write, storage); doc.Save(storageStream); storageStream.Close(); } //var vSlowka = from s in XElement.Load("slowka.xml").Element("slowko").Elements() select s; var v = from s in doc.Descendants("slowko") select new Slowko(s); slowka.AddRange(v); }
public CrawlerQueueEntry Pop() { return AspectF.Define. WriteLock(m_QueueLock). Return(() => { string fileName = m_Store.GetFileNames(Path.Combine(WorkFolderPath, "*")).FirstOrDefault(); if (fileName.IsNullOrEmpty()) { return null; } string path = Path.Combine(WorkFolderPath, fileName); try { using (IsolatedStorageFileStream isoFile = new IsolatedStorageFileStream(path, FileMode.Open, m_Store)) { return isoFile.FromBinary<CrawlerQueueEntry>(); } } finally { m_Store.DeleteFile(path); Interlocked.Decrement(ref m_Count); } }); }
/// <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 cbLiveTile_Click(object sender, RoutedEventArgs e) { if (cbLiveTile.IsChecked.Value) { IsolatedStorageFile directory = IsolatedStorageFile.GetUserStoreForApplication(); if (directory.FileExists("settings.txt")) { using (var myFilestream = new IsolatedStorageFileStream("settings.txt", FileMode.Truncate, IsolatedStorageFile.GetUserStoreForApplication())) using (var writer = new StreamWriter(myFilestream)) { writer.Write("1"); } } CreateLiveTile(); } else { IsolatedStorageFile directory = IsolatedStorageFile.GetUserStoreForApplication(); if (directory.FileExists("settings.txt")) { using (var myFilestream = new IsolatedStorageFileStream("settings.txt", FileMode.Truncate, IsolatedStorageFile.GetUserStoreForApplication())) using (var writer = new StreamWriter(myFilestream)) { writer.Write("0"); } } ResetMainTile(); } }
public void Save(string fileName, string jsonFile) { try { using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { fileName = string.Format("{0}.json", fileName); string filePath = Path.Combine(directory, fileName); if (!store.DirectoryExists(directory)) { store.CreateDirectory(directory); } using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, store)) { using (StreamWriter stream = new StreamWriter(fileStream)) { stream.Write(jsonFile); } } } } catch (IsolatedStorageException exception) { throw exception; } }
public static Yammer.OAuthToken RetrieveAccessToken() { string key; IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication(); using (var isoFileStream = new IsolatedStorageFileStream("key.txt", FileMode.OpenOrCreate, myStore)) { using (var isoFileReader = new StreamReader(isoFileStream)) { key = isoFileReader.ReadToEnd(); } } if (string.IsNullOrWhiteSpace(key)) return null; var keyParts = key.Split('&'); if (keyParts.Length != 2) return null; if (string.IsNullOrWhiteSpace(keyParts[0])) return null; if (string.IsNullOrWhiteSpace(keyParts[1])) return null; return new Yammer.OAuthToken { Key = keyParts[0], Secret = keyParts[1] }; }
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(); } } }
internal static async Task WriteAsync(String path, String content) { var local = IsolatedStorageFile.GetUserStoreForApplication(); var filePath = String.Format(PathFormat, path); if (local.FileExists(filePath)) { using (var isoStoreFile = new IsolatedStorageFileStream(filePath, FileMode.Truncate, FileAccess.Write, local)) { using (var isoStreamWriter = new StreamWriter(isoStoreFile)) { await isoStreamWriter.WriteAsync(content); } } } else { using (var isoStoreFile = new IsolatedStorageFileStream(filePath, FileMode.Create, FileAccess.Write, local)) { using (var isoStreamWriter = new StreamWriter(isoStoreFile)) { await isoStreamWriter.WriteAsync(content); } } } }
public static IList<string> Load(string StorageFileName) { List<string> result = new List<string>(); try { IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication(); if (storageFile.FileExists(StorageFileName)) { using (IsolatedStorageFileStream storageStream = new IsolatedStorageFileStream( StorageFileName, System.IO.FileMode.Open, storageFile)) { using (System.IO.StreamReader reader = new System.IO.StreamReader(storageStream)) { // read settings from isolated storage while (reader.EndOfStream == false) { result.Add(reader.ReadLine()); } } } } return result; } catch { return result; } }
/// <summary> /// Crear in IsolatedStorageFile con la serializacion en binario del diccionario ConfigManager.- /// Este diccionario contiene el par [NombreArchivo,Ruta] /// </summary> private void StoreConfigManager() { //creating a store IsolatedStorageFile userStore = IsolatedStorageFile.GetUserStoreForAssembly(); IsolatedStorageFileStream userStream = new IsolatedStorageFileStream(ConfigManagerFilesUserSettings, FileMode.Create, userStore); SerializeDictionary(userStream, _ConfigManagerFiles); }
private void showImage() { if (App.ViewModel.forShare != null) { imagePicker.Content = App.ViewModel.forShare.ItemName; imagePicker.Opacity = 0.5; System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); //点击超链接后图片存在 if (isf.FileExists(App.ViewModel.forShare.ItemName + ".jpg")) { isf.CopyFile(App.ViewModel.forShare.ItemName + ".jpg", "abc.jpg", true); System.IO.IsolatedStorage.IsolatedStorageFileStream PhotoStream = isf.OpenFile("abc.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read); System.Windows.Media.Imaging.BitmapImage bmp1 = new System.Windows.Media.Imaging.BitmapImage(); bmp1.SetSource(PhotoStream); //把文件流转换为图片 PhotoStream.Close(); //读取完毕,关闭文件流 System.Windows.Media.ImageBrush ib = new System.Windows.Media.ImageBrush(); ib.ImageSource = bmp1; tip.Background = ib; //把图片设置为控件的背景图 //imageTip.Visibility = System.Windows.Visibility.Collapsed; } } //如果存在背景,则显示关联按钮 if (tip.Background != null) { appBar3(); } }
private void SetSourceStr(string sourceStr) { if (imageCache.ContainsKey(sourceStr) == true) { SourceImage.Source = imageCache[sourceStr]; } else { using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { if (isf.FileExists(sourceStr) == false) { SourceImage.Source = null; } else { BitmapImage source = new BitmapImage(); using (IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(sourceStr, System.IO.FileMode.Open, isf)) { source.SetSource(isfStream); } imageCache.Add(sourceStr, source); SourceImage.Source = source; } } } }
public static void ReadSettings( out bool enabled , out bool toast , ArrayList processActions ) { PriorityManagerSettings p; try { XmlSerializer deSerialiser = new XmlSerializer( typeof(PriorityManagerSettings) ); IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream( SettingsFileName , FileMode.Open , FileAccess.Read , FileShare.None ); System.IO.StreamReader reader = new System.IO.StreamReader( fileStream ); p = (PriorityManagerSettings)deSerialiser.Deserialize( reader ); enabled = p.Enabled ; toast = p.ToastEnabled; lock ( processActions.SyncRoot ) { processActions.Clear(); processActions.AddRange( p.ProcessActions ); } reader.Close(); } catch { // hard coded defaults... toast = true; enabled = true; processActions = new ArrayList(); } }
private bool LoadState() { try { using(var store = IsolatedStorageFile.GetUserStoreForApplication()) using(var stream = new IsolatedStorageFileStream(_stateName, FileMode.Open, store)) using(var reader = XmlReader.Create(stream)) { if(reader.ReadToFollowing("State")) { int stateDepth = reader.Depth; reader.Read(); while(reader.Depth > stateDepth) { var key = reader.GetAttribute("Key"); var value = reader.ReadElementContentAsString(); _state[key] = value; } } } AfterStateLoad(this, EventArgs.Empty); return true; } catch { return false; } }
/// <summary> /// Load the location and size of a window from file. If the file is not found, then return the default location and size. /// </summary> /// <param name="filename">The file to store the Rect data.</param> /// <returns>The Rect object.</returns> static public Rect LoadWindowBounds(string filename) { IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly(); try { using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filename, FileMode.Open, storage)) using (StreamReader reader = new StreamReader(stream)) { // Read restore bounds value from file Rect restoreBounds = Rect.Parse(reader.ReadLine()); // if the saved version of rect is not current version, then use the default. string savedUIVersion = reader.ReadLine(); string uiVersion = GetAssemblyVersion(); if (!(string.Compare(uiVersion, savedUIVersion) == 0)) return new Rect(); return restoreBounds; } } catch (FileNotFoundException) { // Handle when file is not found in isolated storage, which is when: // * This is first application session // * The file has been deleted return new Rect(); } catch (System.Exception) { // Handle when other exceptions caught, e.g. cannot parse the file. return new Rect(); } }
protected override void OnLoad(IsolatedStorageFileStream p_File, int p_CurrentVersion) { Read(p_File, out m_OutputMakeFile); Read(p_File, out m_BannerBitmapFile); Read(p_File, out m_TemplateInstallerFile); if (p_CurrentVersion > 2) { Read(p_File, out m_IconFile); } //Version 2 if (p_CurrentVersion > 1) { Read(p_File, out m_TemplateConfigFile); int l_NumberOfTemplates; m_AvailableTemplates.Clear(); Read(p_File, out l_NumberOfTemplates); for (int i = 0; i < l_NumberOfTemplates; i++) { string tmp; Read(p_File, out tmp); m_AvailableTemplates.Add(tmp); } } }
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(); } } }
public void InjectScript() { using(IsolatedStorageFileStream file = new IsolatedStorageFileStream("debugOutput.txt", FileMode.Create, FileAccess.Write, IsolatedStorageFile.GetUserStoreForApplication())) { } if (!hasListener) { PhoneApplicationService.Current.Closing += OnServiceClosing; hasListener = true; } string script = @"(function(win) { function exec(msg) { window.external.Notify('ConsoleLog/' + msg); } var cons = win.console = win.console || {}; cons.log = exec; cons.debug = cons.debug || cons.log; cons.info = cons.info || function(msg) { exec('INFO:' + msg ); }; cons.warn = cons.warn || function(msg) { exec('WARN:' + msg ); }; cons.error = cons.error || function(msg) { exec('ERROR:' + msg ); }; })(window);"; Browser.InvokeScript("execScript", new string[] { script }); }
private void btnLeLog_Click(object sender, RoutedEventArgs e) { mut.WaitOne();//Espera até a thread poder trabalhar ( acessar nosso recurso .txt ); IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication(); if (!isoFile.DirectoryExists("/Logs/")) { mut.ReleaseMutex();// Liebro o meu mutex MessageBox.Show("Nenhum log foi encontrado"); return; } IsolatedStorageFileStream isoLogFileStream = new IsolatedStorageFileStream( "\\Logs\\MeuLog.txt", System.IO.FileMode.Open, isoFile); StreamReader reader = new StreamReader(isoLogFileStream); string log = reader.ReadToEnd(); //Liberar todos os recursos isoLogFileStream.Close(); reader.Close(); // Liebro o meu mutex mut.ReleaseMutex(); MessageBox.Show(log); }
static void Main() { // Создание изолированного хранилища уровня .Net сборки. IsolatedStorageFile userStorage = IsolatedStorageFile.GetUserStoreForAssembly(); // Создание файлового потока с указанием: Имени файла, FileMode, объекта хранилища. IsolatedStorageFileStream userStream = new IsolatedStorageFileStream("UserSettings.set", FileMode.Create, userStorage); // StreamWriter - запись данных в поток userStream. StreamWriter userWriter = new StreamWriter(userStream); userWriter.WriteLine("User Prefs"); userWriter.Close(); // Проверить, если файл существует. string[] files = userStorage.GetFileNames("UserSettings.set"); if (files.Length == 0) { Console.WriteLine("No data saved for this user"); } else { // Прочитать данные из потока. userStream = new IsolatedStorageFileStream("UserSettings.set", FileMode.Open, userStorage); StreamReader userReader = new StreamReader(userStream); string contents = userReader.ReadToEnd(); Console.WriteLine(contents); } // Задержка. Console.ReadKey(); }
public static ObservableCollection<FileViewModel> ReadDataFromIsolatedStorage() { ObservableCollection<FileViewModel> obsColFiles = new ObservableCollection<FileViewModel>(); using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) { if (!storage.FileExists(FilePath)) { return obsColFiles; } using (var isoFileStream = new IsolatedStorageFileStream(FilePath, FileMode.OpenOrCreate, storage)) { using (XmlReader reader = XmlReader.Create(isoFileStream)) { XDocument xml = XDocument.Load(reader); foreach (var file in xml.Root.Elements("File")) { Guid id; Guid.TryParse(file.Attribute("Id").Value, out id); string description = file.Attribute("Description").Value; obsColFiles.Add(new FileViewModel { Description = description, Id = id, IsNew = false }); } return obsColFiles; } } } }
public PropertyFinderPersistentState LoadState() { PropertyFinderPersistentState state = null; try { // load from isolated storage using (var store = IsolatedStorageFile.GetUserStoreForApplication()) using (var stream = new IsolatedStorageFileStream("data.txt", FileMode.OpenOrCreate, FileAccess.Read, store)) using (var reader = new StreamReader(stream)) { if (!reader.EndOfStream) { var serializer = new XmlSerializer(typeof(PropertyFinderPersistentState)); state = (PropertyFinderPersistentState)serializer.Deserialize(reader); // set the persistence service for the newly loaded state state.PersistenceService = this; } } } catch { } // if we cannot retrieve the state, create a new state object if (state == null) { state = new PropertyFinderPersistentState(this); } return state; }
static bool SaveId() { try { #if !OOB using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream storageStream = new IsolatedStorageFileStream(StorageFileName, System.IO.FileMode.Create, storageFile)) { System.IO.StreamWriter writer = new System.IO.StreamWriter(storageStream); // write settings to isolated storage writer.WriteLine(instanceIdGuid.Value.ToString()); writer.Flush(); } return true; } #else if (IsolatedStorageSettings.ApplicationSettings.Contains(StorageKey)) { IsolatedStorageSettings.ApplicationSettings[StorageKey] = instanceIdGuid.Value.ToString(); } else { IsolatedStorageSettings.ApplicationSettings.Add(StorageKey, instanceIdGuid.Value.ToString()); } return true; #endif } catch { // users can disable isolated storage return false; } }
public static UserSettings GetUserPreferences() { IsolatedStorageFileStream fileStream = null; try { var fileLocation = IsolatedStorageFile.GetUserStoreForApplication(); if (fileLocation.FileExists(FileSystem.SettingsFile)) { fileStream = new IsolatedStorageFileStream(FileSystem.SettingsFile, FileMode.Open, fileLocation); var serializer = new XmlSerializer(typeof(UserSettings)); var userSettings = (UserSettings)serializer.Deserialize(fileStream); if (userSettings != null) { return userSettings; } else { throw new Exception("Unable lo load user preferences"); } } else { var settings = new UserSettings(); UpdateUserSettings(settings); return settings; } } finally { if (fileStream!=null) { fileStream.Close(); } } }
public static void LoadIconPositions() { try { using (var isoStore = IsolatedStorageFile.GetUserStoreForAssembly()) using (var stream = new IsolatedStorageFileStream(IconPositionsFile, FileMode.Open, isoStore)) using (var textStream = new StreamReader(stream)) { string line; _desktopIconPositions = new Dictionary<string, Point>(); while ((line = textStream.ReadLine()) != null) { var items = line.Split(null, 3); var point = new Point { X = Convert.ToInt32(items[0], CultureInfo.InvariantCulture), Y = Convert.ToInt32(items[1], CultureInfo.InvariantCulture) }; _desktopIconPositions.Add(items[2], point); } } } catch (Exception ex) { Program.LogError(ex.Message); _desktopIconPositions = new Dictionary<string, Point>(); } }
private void Image_Tap(object sender, GestureEventArgs e) { var file = (RingtoneListItem)((Image)sender).DataContext; if (file != null && !file.DisplayName.Contains("none")) { #if ARM string fileName = Path.GetFileName(file.FullPath); try { // Copy file to the isf if (!_isoStore.FileExists(fileName)) { SystemTray.ProgressIndicator.IsVisible = true; File.Copy(file.FullPath, Path.Combine(_isoRootPath, fileName), true); } using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Open, _isoStore)) { mediaElement.SetSource(isoStream); mediaElement.Play(); SystemTray.ProgressIndicator.IsVisible = false; } } catch { } #else MessageBox.Show(file.FullPath); #endif } }
public static void Run() { Console.WriteLine("Q71 Start:"); try { using (var isoFile = IsolatedStorageFile.GetMachineStoreForAssembly()) using (var isoStream = new IsolatedStorageFileStream("Settings.dat", FileMode.Create, isoFile)) using (var writer = new StreamWriter(isoStream)) { writer.Write("Contents of Settings.dat"); } using (var isoFile = IsolatedStorageFile.GetMachineStoreForAssembly()) using (var isoStream = new IsolatedStorageFileStream("Settings.dat", FileMode.Open, isoFile)) using (var reader = new StreamReader(isoStream)) { var result = reader.ReadToEnd(); Console.WriteLine(result); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\nQ71 End..."); Console.ReadKey(); }
protected override void LoadTasks() { var file = IsolatedStorageFile.GetUserStoreForAssembly(); _tasks = null; using(var stream = new IsolatedStorageFileStream( TasksFileName, FileMode.OpenOrCreate, FileAccess.Read, file)) { var reader = new XmlTextReader(stream); var serializer = new XmlSerializer(typeof(List<Task>)); try { _tasks= serializer.Deserialize(reader) as List<Task>; } catch (Exception) { _tasks = new List<Task>(); } finally { reader.Close(); } if (_tasks.Count == 0) _lastId = 0; else _lastId = _tasks.Max(t => t.TaskId); } }
private void RestoreFromFile(Stream file) { // // using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { using (var zip = new ZipInputStream(file)) { try { while (true) { var ze = zip.GetNextEntry(); if (ze == null) break; using (var f = new IsolatedStorageFileStream(ze.Name, FileMode.Create, store)) { var fs = new byte[ze.Size]; zip.Read(fs, 0, fs.Length); f.Write(fs, 0, fs.Length); } } } catch { lblLastBackup.Text = StringResources.BackupAndRestorePage_Messages_RestoreFailed; App.ToastMe(StringResources.BackupAndRestorePage_Messages_RestoreFailed); return; } finally { file.Close(); ClearOldBackupFiles(); App.ViewModel.IsRvDataChanged = true; } } } lblLastBackup.Text = StringResources.BackupAndRestorePage_Messages_RestoreSuccess; App.ToastMe(StringResources.BackupAndRestorePage_Messages_RestoreSuccess); }
protected override string ReadTextFile(string filename) { String result = null; try { using (var isoStore = IsolatedStorageFile.GetStore(Scope, null, null)) { if (isoStore.FileExists(filename)) { using (var stream = new IsolatedStorageFileStream(filename, FileMode.Open, isoStore)) { long length = stream.Length; StreamReader reader = new StreamReader(stream); result = reader.ReadToEnd(); } } } } catch (Exception) { //log.Error("Cannot read application settings from isolated storage file", e); } return result; }
public override IAsyncResult BeginDownloadXml(Uri feeduri, AsyncCallback callback) { #if !WINDOWS_PHONE if (!IsolatedStorageFile.IsEnabled) throw new MissingFeedException("IsolatedStorage is not enabled! Cannot access files from IsolatedStorage!"); #endif try { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { if(!PingFeed(feeduri, store)) throw new MissingFeedException(string.Format("Could not find feed at location {0}", feeduri)); using (var stream = new IsolatedStorageFileStream(feeduri.OriginalString, FileMode.Open, FileAccess.Read, store)) { using(var reader = new StreamReader(stream)) { var strOutput = reader.ReadToEnd(); //Fake the async result var result = new AsyncResult<FeedTuple>(callback, new FeedTuple { FeedContent = strOutput, FeedUri = feeduri }, true); if (callback != null) callback.Invoke(result); return result; } } } } catch (IsolatedStorageException ex) { throw new MissingFeedException(string.Format("Unable to open feed at {0}", feeduri), ex); } }
public void LoadSettings() { try { IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null); if (!isoStore.FileExists(SettingsFileName)) return; using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(SettingsFileName, FileMode.Open, FileAccess.Read, isoStore)) using (StreamReader sr = new StreamReader(isoStream)) { string settings = sr.ReadToEnd(); XElement element = XElement.Parse(settings); //Dictionary<string, string> newSettings = new Dictionary<string, string>(); Settings = (from field in element.Elements("appSettings").Elements() select new { Name = field.Name.ToString(), field.Value }).ToDictionary(x => x.Name, x => x.Value); } } catch { } }
static void Main(string[] args) { IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForAssembly(); IsolatedStorageFileStream isoFile = new IsolatedStorageFileStream("myfile.txt", FileMode.Create, isoStore); Console.WriteLine(isoFile.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(isoFile).ToString()); StreamWriter sw = new StreamWriter(isoFile); sw.WriteLine("This text is written to an isolated storage file."); sw.Close(); isoFile.Close(); isoFile = new IsolatedStorageFileStream("myfile.txt", FileMode.Open, isoStore); StreamReader sr = new StreamReader(isoFile); Console.WriteLine(sr.ReadToEnd()); sr.Close(); isoFile.Close(); }
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(); } } }
public static void WriteStream(Stream stream, System.IO.IsolatedStorage.IsolatedStorageFileStream fileStream) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0) { fileStream.Write(buffer, 0, bytesRead); } }
public string Read(string filename) { string result = string.Empty; System.IO.IsolatedStorage.IsolatedStorageFile isoStore = System.IO.IsolatedStorage.IsolatedStorageFile. GetUserStoreForDomain(); try { // Checks to see if the options.txt file exists. if (isoStore.GetFileNames(filename).GetLength(0) != 0) { // Opens the file because it exists. System.IO.IsolatedStorage.IsolatedStorageFileStream isos = new System.IO.IsolatedStorage.IsolatedStorageFileStream (filename, System.IO.FileMode.Open, isoStore); System.IO.StreamReader reader = null; try { reader = new System.IO.StreamReader(isos); // Reads the values stored. result = reader.ReadLine(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine ("Cannot read options " + ex.ToString()); } finally { reader.Close(); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine ("Cannot read options " + ex.ToString()); } return(result); }
// Writes the button options to the isolated storage. public void Write(string filename, string content) { System.IO.IsolatedStorage.IsolatedStorageFile isoStore = System.IO.IsolatedStorage.IsolatedStorageFile. GetUserStoreForDomain(); try { // Checks if the file exists and, if it does, tries to delete it. if (isoStore.GetFileNames(filename).GetLength(0) != 0) { isoStore.DeleteFile(filename); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine ("Cannot delete file " + ex.ToString()); } // Creates the options file and writes the button options to it. System.IO.StreamWriter writer = null; try { System.IO.IsolatedStorage.IsolatedStorageFileStream isos = new System.IO.IsolatedStorage.IsolatedStorageFileStream(filename, System.IO.FileMode.CreateNew, isoStore); writer = new System.IO.StreamWriter(isos); writer.WriteLine(content); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine ("Cannot write options " + ex.ToString()); } finally { writer.Close(); } }
private void showBackground() { System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); //点击超链接后图片存在 if (isf.FileExists("back_temp.jpg")) { System.IO.IsolatedStorage.IsolatedStorageFileStream PhotoStream = isf.OpenFile("back_temp.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read); System.Windows.Media.Imaging.BitmapImage bmp1 = new System.Windows.Media.Imaging.BitmapImage(); bmp1.SetSource(PhotoStream); //把文件流转换为图片 PhotoStream.Close(); //读取完毕,关闭文件流 System.Windows.Media.ImageBrush ib = new System.Windows.Media.ImageBrush(); ib.ImageSource = bmp1; MainPano.Background = ib; //把图片设置为控件的背景图 //imageTip.Visibility = System.Windows.Visibility.Collapsed; } // else // { // MainPano.Background = null; // } }
/// <summary> /// 保存信息至本地文件,SilverLight缓存中 /// </summary> /// <param name="rFileName">存储文件名</param> /// <param name="rText">消息文本</param> public static void WriteSlTextFile(string rFileName, string rText) { System.IO.IsolatedStorage.IsolatedStorageFile isf = null; System.IO.Stream stream = null; System.IO.TextWriter writer = null; try { isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); if (rFileName.IndexOf(':') >= 0) { rFileName = rFileName.Substring(rFileName.LastIndexOf(':') + 1); } string rPath = System.IO.Path.GetDirectoryName(rFileName); if (isf.DirectoryExists(rPath) == false) { isf.CreateDirectory(rPath); } stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, isf); //stream.Seek(0, System.IO.SeekOrigin.End); writer = new System.IO.StreamWriter(stream); writer.Write(rText); writer.Flush(); } finally { try { writer.Close(); stream.Close(); isf.Dispose(); } catch { } } }
/// <summary> /// 读取本地文件信息,SilverLight缓存中 /// </summary> /// <param name="rFileName">存储文件名</param> /// <returns>返回消息文本</returns> public static string ReadSlTextFile(string rFileName) { System.IO.IsolatedStorage.IsolatedStorageFile isf = null; System.IO.Stream stream = null; System.IO.TextReader reader = null; try { isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); stream = new System.IO.IsolatedStorage.IsolatedStorageFileStream(rFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, isf); reader = new System.IO.StreamReader(stream); string sLine = reader.ReadToEnd(); //string sLine=reader.ReadLine(); return(sLine); } catch { return(string.Empty); } finally { try { if (reader != null) { reader.Close(); // Close the reader } if (reader != null) { stream.Close(); }// Close the stream isf.Dispose(); } catch { } } }
void PhotoTask_Completed(object sender, PhotoResult e) { if (e.TaskResult == TaskResult.OK && e.ChosenPhoto != null) { System.Windows.Media.Imaging.WriteableBitmap bmp = Microsoft.Phone.PictureDecoder.DecodeJpeg(e.ChosenPhoto); System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); if (isf.FileExists("abc.jpg")) { isf.DeleteFile("abc.jpg"); } System.IO.IsolatedStorage.IsolatedStorageFileStream PhotoStream = isf.CreateFile("abc.jpg"); System.Windows.Media.Imaging.Extensions.SaveJpeg(bmp, PhotoStream, 432, 645, 0, 100); //这里设置保存后图片的大小、品质 PhotoStream.Close(); //写入完毕,关闭文件流 PhotoStream = isf.OpenFile("abc.jpg", System.IO.FileMode.Open, System.IO.FileAccess.Read); //读取刚刚保存的图片的文件流 System.Windows.Media.Imaging.BitmapImage bmp1 = new System.Windows.Media.Imaging.BitmapImage(); bmp1.SetSource(PhotoStream); //把文件流转换为图片 PhotoStream.Close(); //读取完毕,关闭文件流 System.Windows.Media.ImageBrush ib = new System.Windows.Media.ImageBrush(); ib.ImageSource = bmp1; tip.Background = ib;//把图片设置为控件的背景图 imageTip.Visibility = System.Windows.Visibility.Collapsed; if (imagePicker.Content.ToString() == txtnote.Resources.StringLibrary.imagename) { if (MessageBox.Show(txtnote.Resources.StringLibrary.imagename, txtnote.Resources.StringLibrary.guanlian, MessageBoxButton.OKCancel) == MessageBoxResult.OK) { NavigationService.Navigate(new Uri("/txtnote;component/Pick.xaml", UriKind.Relative)); } } else { appBar3(); } } }
/// <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 { } } }
private void UploadFile() { var updateIe = App.ViewModel.AllToUpdateItems.AsQueryable(); client.UploadCompleted += client_UploadCompleted; System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication(); foreach (ToDoItem uploadItem in updateIe) { infoTextBlock.Text = "Uploading..."; byte[] b2 = System.Text.Encoding.UTF8.GetBytes(uploadItem.TxtFile); MemoryStream file = new MemoryStream(b2); //不同difference client.UploadAsync(skyDriveFolderID, uploadItem.ItemName, file, OverwriteOption.Overwrite); string imagename = uploadItem.ItemName + ".jpg"; if (isf.FileExists(imagename)) { System.IO.IsolatedStorage.IsolatedStorageFileStream PhotoStream = isf.OpenFile(imagename, System.IO.FileMode.Open, System.IO.FileAccess.Read); client.UploadAsync(skyDriveFolderID_image, imagename, PhotoStream, OverwriteOption.Overwrite); } } }
public static string ReadAllText(this IsolatedStorageFileStream stream) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); return(Encoding.UTF8.GetString(buffer)); }
public static void WriteAllText(this IsolatedStorageFileStream stream, string content) { byte[] buffer = Encoding.UTF8.GetBytes(content); stream.Write(buffer, offset: 0, count: buffer.Length); }
/// <summary>Initializes a new instance of the <see cref="T:System.IO.IsolatedStorage.IsolatedStorageFileStream" /> class giving access to the file designated by <paramref name="path" />, in the specified <paramref name="mode" />, with the specified file <paramref name="access" />, using the file sharing mode specified by <paramref name="share" />, with the <paramref name="buffersize" /> specified, and in the context of the <see cref="T:System.IO.IsolatedStorage.IsolatedStorageFile" /> specified by <paramref name="isf" />.</summary> /// <param name="path">The relative path of the file within isolated storage. </param> /// <param name="mode">One of the <see cref="T:System.IO.FileMode" /> values. </param> /// <param name="access">A bitwise combination of the <see cref="T:System.IO.FileAccess" /> values. </param> /// <param name="share">A bitwise combination of the <see cref="T:System.IO.FileShare" /> values </param> /// <param name="bufferSize">The <see cref="T:System.IO.FileStream" /> buffer size. </param> /// <param name="isf">The <see cref="T:System.IO.IsolatedStorage.IsolatedStorageFile" /> in which to open the <see cref="T:System.IO.IsolatedStorage.IsolatedStorageFileStream" />. </param> /// <exception cref="T:System.ArgumentException">The <paramref name="path" /> is badly formed. </exception> /// <exception cref="T:System.ArgumentNullException">The <paramref name="path" /> is null. </exception> /// <exception cref="T:System.IO.FileNotFoundException">No file was found and the <paramref name="mode" /> is set to <see cref="F:System.IO.FileMode.Open" />. </exception> /// <exception cref="T:System.IO.IsolatedStorage.IsolatedStorageException"> /// <paramref name="isf" /> does not have a quota. </exception> public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf) : base(IsolatedStorageFileStream.CreateIsolatedPath(isf, path, mode), mode, access, share, bufferSize, false, true) { }