private async void OnWrite(Object sender, RoutedEventArgs e) { // 获取本地目录的引用 StorageFolder local = ApplicationData.Current.LocalFolder; // 创建新文件 StorageFile newFIle = await local.CreateFileAsync("demo.dat", CreationCollisionOption.ReplaceExisting); // 打开文件流 using(IRandomAccessStream stream = await newFIle.OpenAsync(FileAccessMode.ReadWrite)) { // 实例化 DataWriter DataWriter dw = new DataWriter(stream); // 设置默认编码格式 dw.UnicodeEncoding = UnicodeEncoding.Utf8; // 写入 bool 值 dw.WriteBoolean(true); // 写入日期值 DateTime dt = new DateTime(2010, 8, 21); dw.WriteDateTime(dt); // 写入字符串 string str = "测试文本"; // 计算字符串长度 uint len = dw.MeasureString(str); // 先写入字符串的长的 dw.WriteUInt32(len); // 再写入字符串 dw.WriteString(str); // 以下方法必须调用 await dw.StoreAsync(); // 解除 DataWriter 与流的关联 dw.DetachStream(); dw.Dispose(); } MessageDialog msgDlg = new MessageDialog("保存成功。"); await msgDlg.ShowAsync(); }
/// <summary> /// Saves the current progress state for the current dictionary /// </summary> public void saveState() { if (string.IsNullOrEmpty(mCrammerDict.StateFile)) throw new Exception("No state file available"); try { using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream()) { using (DataWriter dataWriter = new DataWriter(memoryStream)) { dataWriter.WriteInt32(mTotalWords); dataWriter.WriteInt32(mKnownWords); dataWriter.WriteInt32(mStart); dataWriter.WriteInt32(mCurrentWord); dataWriter.WriteBoolean(mNewWordsInUse); dataWriter.WriteInt32(mInSystem); dataWriter.WriteBoolean(mSwapSequence); dataWriter.WriteBoolean(mReachedEnd); mNewWordsChamber.saveState(dataWriter); mFirstChamber.saveState(dataWriter); mSecondChamber.saveState(dataWriter); mThirdChamber.saveState(dataWriter); mFourthChamber.saveState(dataWriter); mFifthChamber.saveState(dataWriter); mCompletedChamber.saveState(dataWriter); IBuffer stateBuffer = dataWriter.DetachBuffer(); string stateString = BinaryBufferConverter.getStringFromBuffer(stateBuffer); mCrammerDict.setStateFile(stateString); } } } catch (Exception) { // Assume mismatch with chamber-size config and contents of .STA file. // Delete it so that the dictionary will load successfully next time. mCrammerDict.removeStateFile(); } mRestoredState = true; }
private async Task WriteStatus(bool state) { StorageFolder storageFolder = ApplicationData.Current.LocalFolder; StorageFile file = await storageFolder.CreateFileAsync("status.txt", CreationCollisionOption.ReplaceExisting); var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); using (var outputStream = stream.GetOutputStreamAt(0)) { using (var dataWriter = new DataWriter(outputStream)) { dataWriter.WriteBoolean(state); await dataWriter.StoreAsync(); await outputStream.FlushAsync(); } } stream.Dispose(); }