/// <summary> /// Dequeue the first record /// </summary> public static RequestRecord DequeueRequestRecord() { List<RequestRecord> requests = new List<RequestRecord>(); DataContractJsonSerializer dc = new DataContractJsonSerializer(requests.GetType()); using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication()) { lock (fileLock) { using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(@"RequestRecords.xml", FileMode.Open, file)) { try { // if the file opens, read the contents requests = dc.ReadObject(stream) as List<RequestRecord>; if (requests.Count > 0) { RequestRecord record = requests[0]; requests.Remove(record); // remove the first entry stream.SetLength(0); stream.Position = 0; dc.WriteObject(stream, requests); record.DeserializeBody(); return record; } else return null; } catch (Exception) { stream.Position = 0; string s = new StreamReader(stream).ReadToEnd(); return null; } } } } }
/// <summary>Saves data written to the current <see cref="T:System.IO.IsolatedStorage.IsolatedStorageSettings" /> object.</summary> /// <exception cref="T:System.IO.IsolatedStorage.IsolatedStorageException">The <see cref="T:System.IO.IsolatedStorage.IsolatedStorageFile" /> does not have enough available free space.</exception> public void Save() { using (IsolatedStorageFileStream stream = this._appStore.OpenFile("__LocalSettings", FileMode.OpenOrCreate)) { using (MemoryStream stream2 = new MemoryStream()) { Dictionary <Type, bool> dictionary = new Dictionary <Type, bool>(); StringBuilder builder = new StringBuilder(); foreach (object obj2 in this._settings.Values) { if (obj2 != null) { Type type = obj2.GetType(); if (!type.IsPrimitive && (type != typeof(string))) { dictionary[type] = true; if (builder.Length > 0) { builder.Append('\0'); } builder.Append(type.AssemblyQualifiedName); } } } builder.Append(Environment.NewLine); byte[] bytes = Encoding.UTF8.GetBytes(builder.ToString()); stream2.Write(bytes, 0, bytes.Length); new DataContractSerializer(typeof(Dictionary <string, object>), dictionary.Keys).WriteObject(stream2, this._settings); if (stream2.Length > (this._appStore.AvailableFreeSpace + stream.Length)) { throw new IsolatedStorageException("Not enough space in isolated storage."); } stream.SetLength(0L); byte[] buffer = stream2.ToArray(); stream.Write(buffer, 0, buffer.Length); } } }
public void write(string options) { try { try { fileOptions = JSON.JsonHelper.Deserialize<FileOptions>(options); } catch (Exception e) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } if (string.IsNullOrEmpty(fileOptions.Data)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create the file if not exists if (!isoFile.FileExists(fileOptions.FilePath)) { var file = isoFile.CreateFile(fileOptions.FilePath); file.Close(); } using (FileStream stream = new IsolatedStorageFileStream(fileOptions.FilePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= fileOptions.Position && fileOptions.Position < stream.Length) { stream.SetLength(fileOptions.Position); } using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Seek(0, SeekOrigin.End); writer.Write(fileOptions.Data.ToCharArray()); } } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, fileOptions.Data.Length)); } catch (ArgumentException e) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new ErrorCode(ENCODING_ERR))); } catch (IsolatedStorageException e) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new ErrorCode(INVALID_MODIFICATION_ERR))); } catch (SecurityException e) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new ErrorCode(SECURITY_ERR))); } catch (Exception e) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new ErrorCode(NOT_READABLE_ERR))); } }
public void truncate(string options) { try { try { fileOptions = JSON.JsonHelper.Deserialize<FileOptions>(options); } catch (Exception e) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } long streamLength = 0; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(fileOptions.FilePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new ErrorCode(NOT_FOUND_ERR))); return; } using (FileStream stream = new IsolatedStorageFileStream(fileOptions.FilePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= fileOptions.Size && fileOptions.Size < stream.Length) { stream.SetLength(fileOptions.Size); } streamLength = stream.Length; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, streamLength)); } catch (ArgumentException e) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new ErrorCode(ENCODING_ERR))); } catch (SecurityException e) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new ErrorCode(SECURITY_ERR))); } catch (Exception e) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new ErrorCode(NOT_READABLE_ERR))); } }
//write:[filePath,data,position,isBinary,callbackId] public void write(string options) { string[] optStrings = getOptionStrings(options); string filePath = optStrings[0]; string data = optStrings[1]; int position = int.Parse(optStrings[2]); bool isBinary = bool.Parse(optStrings[3]); string callbackId = optStrings[4]; try { if (string.IsNullOrEmpty(data)) { Debug.WriteLine("Expected some data to be send in the write command to {0}", filePath); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), callbackId); return; } byte[] dataToWrite = isBinary ? JSON.JsonHelper.Deserialize<byte[]>(data) : System.Text.Encoding.UTF8.GetBytes(data); using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create the file if not exists if (!isoFile.FileExists(filePath)) { var file = isoFile.CreateFile(filePath); file.Close(); } using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= position && position <= stream.Length) { stream.SetLength(position); } using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Seek(0, SeekOrigin.End); writer.Write(dataToWrite); } } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, dataToWrite.Length), callbackId); } catch (Exception ex) { if (!this.HandleException(ex, callbackId)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR), callbackId); } } }
private static void SaveDocument(XmlDocument document, string filename) { IsolatedStorageFileStream storageFileStream = new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, FileAccess.Write); storageFileStream.SetLength(0L); XmlTextWriter xmlTextWriter = new XmlTextWriter((Stream)storageFileStream, (Encoding)new UnicodeEncoding()); xmlTextWriter.Formatting = Formatting.Indented; document.Save((XmlWriter)xmlTextWriter); xmlTextWriter.Close(); storageFileStream.Close(); }
private static Guid GetOrCreateOriginIdentity() { Requires.ValidState(file != null); Contract.Ensures(Contract.Result<Guid>() != Guid.Empty); Guid identityGuid = Guid.Empty; const int GuidLength = 16; using (var identityFileStream = new IsolatedStorageFileStream("identity.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, file)) { if (identityFileStream.Length == GuidLength) { byte[] guidBytes = new byte[GuidLength]; if (identityFileStream.Read(guidBytes, 0, GuidLength) == GuidLength) { identityGuid = new Guid(guidBytes); } } if (identityGuid == Guid.Empty) { identityGuid = Guid.NewGuid(); byte[] guidBytes = identityGuid.ToByteArray(); identityFileStream.SetLength(0); identityFileStream.Write(guidBytes, 0, guidBytes.Length); } return identityGuid; } }
/// <summary> /// 向指定的文件位置处写数据 /// </summary> /// <param name="filePath">指定文件</param> /// <param name="data">待写数据</param> /// <param name="position">指定位置</param> /// <param name="errCode">返回操作错误码对象</param> /// <returns>成功返回写数据的长度,相反返回0</returns> public int Write(string filePath, string data, int position, out ErrorCode errCode) { if (null == filePath) { XLog.WriteError("Write filePath can'n be null, with INVALID_MODIFICATION_ERR"); errCode = new ErrorCode(INVALID_MODIFICATION_ERR); return 0; } try { if (string.IsNullOrEmpty(data)) { XLog.WriteError("Write Expected some data to be send in the write command to " + filePath); errCode = new ErrorCode(INVALID_MODIFICATION_ERR); return 0; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create the file if not exists if (!isoFile.FileExists(filePath)) { var file = isoFile.CreateFile(filePath); file.Close(); } using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= position && position <= stream.Length) { stream.SetLength(position); } using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Seek(0, SeekOrigin.End); writer.Write(data.ToCharArray()); } } } errCode = null; return data.Length; } catch (DirectoryNotFoundException ex) { XLog.WriteError("Write file filePath " + filePath + " occur Exception " + ex.Message); errCode = new ErrorCode(NOT_FOUND_ERR); return 0; } catch (Exception ex) { if (ex is IsolatedStorageException || ex is ObjectDisposedException || ex is ArgumentException || ex is IOException || ex is ArgumentOutOfRangeException || ex is NotSupportedException) { XLog.WriteError(string.Format("Write data {0} to file {1} occur Exception {2}", data, filePath, ex.Message)); errCode = new ErrorCode(NOT_READABLE_ERR); return 0; } throw ex; } }
public void truncate(string options) { // TODO: try/catch string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options); string filePath = optStrings[0]; int size = int.Parse(optStrings[1]); try { long streamLength = 0; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR)); return; } using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= size && size <= stream.Length) { stream.SetLength(size); } streamLength = stream.Length; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, streamLength)); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR)); } } }
/// <summary> /// Enqueue a Web Service record into the record queue /// </summary> public static void EnqueueRequestRecord(RequestRecord newRecord) { bool enableQueueOptimization = false; // turn off the queue optimization (doesn't work with introduction of tags) List<RequestRecord> requests = new List<RequestRecord>(); DataContractJsonSerializer dc = new DataContractJsonSerializer(requests.GetType()); if (newRecord.SerializedBody == null) newRecord.SerializeBody(); using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication()) { lock (fileLock) { // if the file opens, read the contents using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(@"RequestRecords.xml", FileMode.OpenOrCreate, file)) { try { // if the file opened, read the record queue requests = dc.ReadObject(stream) as List<RequestRecord>; if (requests == null) requests = new List<RequestRecord>(); } catch (Exception) { stream.Position = 0; string s = new StreamReader(stream).ReadToEnd(); } if (enableQueueOptimization == true) { OptimizeQueue(newRecord, requests); } else { // this is a new record so add the new record at the end requests.Add(newRecord); } // reset the stream and write the new record queue back to the file stream.SetLength(0); stream.Position = 0; dc.WriteObject(stream, requests); stream.Flush(); } } } }
/// <summary> /// Method to save tokens to isolated storage /// </summary> /// <remarks></remarks> private void SaveToFile() { // Get an isolated store for user and application IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore( IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null); // Create a file var isoStream = new IsolatedStorageFileStream(CsTokensFile, FileMode.OpenOrCreate, FileAccess.Write, isoStore); isoStream.SetLength(0); //Position to overwrite the old data. // Write tokens to file var writer = new StreamWriter(isoStream); writer.Write(JsonConvert.SerializeObject(_tokens)); writer.Close(); isoStore.Dispose(); isoStore.Close(); }
private void Write (string filename) { byte[] buffer = new byte[8]; using (IsolatedStorageFileStream write = new IsolatedStorageFileStream (filename, FileMode.Create, FileAccess.Write)) { Assert.IsFalse (write.CanRead, "write.CanRead"); Assert.IsTrue (write.CanSeek, "write.CanSeek"); Assert.IsTrue (write.CanWrite, "write.CanWrite"); Assert.IsFalse (write.IsAsync, "write.IsAync"); write.Write (buffer, 0, buffer.Length); write.Position = 0; write.WriteByte ((byte)buffer.Length); write.SetLength (8); write.Flush (); write.Close (); } }
public void write(string options) { if (!LoadFileOptions(options)) { return; } try { if (string.IsNullOrEmpty(fileOptions.Data)) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create the file if not exists if (!isoFile.FileExists(fileOptions.FilePath)) { var file = isoFile.CreateFile(fileOptions.FilePath); file.Close(); } using (FileStream stream = new IsolatedStorageFileStream(fileOptions.FilePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= fileOptions.Position && fileOptions.Position < stream.Length) { stream.SetLength(fileOptions.Position); } using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Seek(0, SeekOrigin.End); writer.Write(fileOptions.Data.ToCharArray()); } } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, fileOptions.Data.Length)); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR)); } } }
public void truncate(string options) { if (!LoadFileOptions(options)) { return; } try { long streamLength = 0; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(fileOptions.FilePath)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_FOUND_ERR)); return; } using (FileStream stream = new IsolatedStorageFileStream(fileOptions.FilePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= fileOptions.Size && fileOptions.Size < stream.Length) { stream.SetLength(fileOptions.Size); } streamLength = stream.Length; } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, streamLength)); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR)); } } }
public void ResizeFile() { const int blocks = 10000; int blockcount = Blocks.Count; for (int i = 0; i < blocks; i++) { Blocks.Add(blockcount + i, true); } using (var fs = new IsolatedStorageFileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, isf)) { fs.SetLength(fs.Length + (blocks * BlockSize)); fs.Flush(); } }
public void SetLength () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication (); using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream ("moon", FileMode.Create, isf)) { fs.SetLength (1); isf.Remove (); // this removed everything Assert.Throws (delegate { fs.SetLength (1); }, typeof (IsolatedStorageException), "Remove/Write"); // Fails in Silverlight 3 isf.Dispose (); Assert.Throws (delegate { fs.SetLength (1); }, typeof (ObjectDisposedException), "Dispose/Write"); } isf = IsolatedStorageFile.GetUserStoreForApplication (); Assert.AreEqual (0, isf.GetFileNames ().Length, "Empty"); }
public void PlayingWithQuota () { IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication (); try { using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream ("moon", FileMode.Create, isf)) { // funny (in a strange way) but this works (up to 1024 bytes) fs.SetLength (isf.AvailableFreeSpace + 1024); fs.SetLength (0); // reset Assert.Throws (delegate { fs.SetLength (isf.AvailableFreeSpace + 1025); }, typeof (IsolatedStorageException), ">1024"); // this does not since AvailableFreeSpace < Quota (overhead?) // KnownFailure because Moonlight, right now, has AvailableFreeSpace = Quota - 1024 (Safety) while SL has some "extra" stuff (less space) // Assert.Throws (delegate { fs.SetLength (isf.Quota); }, typeof (IsolatedStorageException), "OverQuota"); } } finally { // ensure other tests can run properly isf.Remove (); } }
//write:["filePath","data","position"], public void write(string options) { // TODO: try/catch string[] optStrings = JSON.JsonHelper.Deserialize<string[]>(options); string filePath = optStrings[0]; string data = optStrings[1]; int position = int.Parse(optStrings[2]); try { if (string.IsNullOrEmpty(data)) { Debug.WriteLine("Expected some data to be send in the write command to {0}", filePath); DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); return; } using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { // create the file if not exists if (!isoFile.FileExists(filePath)) { var file = isoFile.CreateFile(filePath); file.Close(); } using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= position && position <= stream.Length) { stream.SetLength(position); } using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Seek(0, SeekOrigin.End); writer.Write(data.ToCharArray()); } } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, data.Length)); } catch (Exception ex) { if (!this.HandleException(ex)) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, NOT_READABLE_ERR)); } } }
/// <summary> /// 截取指定大小文件 /// </summary> /// <param name="filePath">指定文件</param> /// <param name="size">截取大小</param> /// <param name="errCode">返回操作错误码对象</param> /// <returns>返回截取后文件大小</returns> public long Truncate(string filePath, int size, out ErrorCode errCode) { if (null == filePath) { XLog.WriteError("Truncate filePath can'n be null, with INVALID_MODIFICATION_ERR"); errCode = new ErrorCode(INVALID_MODIFICATION_ERR); return 0; } try { long streamLength = 0; using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isoFile.FileExists(filePath)) { XLog.WriteError(string.Format("Truncate file {0} to with NOT_FOUND_ERR", filePath)); errCode = new ErrorCode(NOT_FOUND_ERR); return 0; } using (FileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, FileAccess.ReadWrite, isoFile)) { if (0 <= size && size <= stream.Length) { stream.SetLength(size); } streamLength = stream.Length; } } errCode = null; return streamLength; } catch (Exception ex) { if (ex is IsolatedStorageException || ex is ObjectDisposedException || ex is ArgumentException || ex is IOException || ex is ArgumentOutOfRangeException || ex is NotSupportedException) { XLog.WriteError(string.Format("Truncate file {0} to size {1} occur Exception {2}", filePath, size, ex.Message)); errCode = new ErrorCode(NOT_READABLE_ERR); return 0; } throw ex; } }