public async void SavePresets() { String json_str = Serial.JsonHelper.ToJson(m_Presets, m_Presets.GetType()); var picker = new Windows.Storage.Pickers.FileSavePicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as picker.FileTypeChoices.Add("JSON", new List <string>() { ".json" }); // Default file name if the user does not type one in or select a file to replace picker.SuggestedFileName = "GenCodePreset"; var t_storagefile = await picker.PickSaveFileAsync(); if (t_storagefile == null) { return; } using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(transaction.Stream)) { dataWriter.WriteString(json_str); transaction.Stream.Size = await dataWriter.StoreAsync(); await transaction.Stream.FlushAsync(); await transaction.CommitAsync(); } } }
// Write Stream(通过 StorageStreamTransaction 写) private async void btnWriteStream2_Click(object sender, RoutedEventArgs e) { // 在指定的目录下创建指定的文件 StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null, KnownFolderId.DocumentsLibrary); StorageFile storageFile = await storageFolder.CreateFileAsync("webabcdStream.txt", CreationCollisionOption.ReplaceExisting); string textContent = "I am webabcd(StorageStreamTransaction)"; using (StorageStreamTransaction transaction = await storageFile.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(transaction.Stream)) { // 将字符串写入数据流 dataWriter.WriteString(textContent); // 使用 StorageStreamTransaction 方式的话,调用 DataWriter 的 StoreAsync() 方法的作用是把数据写入临时文件 // 以本例为例,这个临时文件就是同目录下名为 webabcdStream.txt.~tmp 的文件。只要不调用 CommitAsync() 方法的话就会看到 // 返回值为写入数据的大小,需要通过此值更新 StorageStreamTransaction 中的 Stream 的大小 transaction.Stream.Size = await dataWriter.StoreAsync(); // 重命名临时文件 await transaction.CommitAsync(); lblMsg.Text = "写入成功"; } } }
private async void C_BUTTON_LOAD_ENTITY_Click(object sender,RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as picker.FileTypeFilter.Add(".json"); // Default file name if the user does not type one in or select a file to replace var t_storagefile = await picker.PickSingleFileAsync(); if (t_storagefile == null) { return; } String json_str; using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(transaction.Stream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)transaction.Stream.Size); json_str = dataReader.ReadString(numBytesLoaded); await transaction.Stream.FlushAsync(); await transaction.CommitAsync(); } } Deserialize(json_str); }
private async void C_BUTTON_GENCODE_ENTITY_Click(object sender,RoutedEventArgs e) { String res = m_Elements.GenFunctions(); var picker = new Windows.Storage.Pickers.FileSavePicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as picker.FileTypeChoices.Add("cs",new List <string>() { ".cs" }); // Default file name if the user does not type one in or select a file to replace picker.SuggestedFileName = "gencode"; var t_storagefile = await picker.PickSaveFileAsync(); if (t_storagefile == null) { return; } using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(transaction.Stream)) { dataWriter.WriteString(res); transaction.Stream.Size = await dataWriter.StoreAsync(); await transaction.Stream.FlushAsync(); await transaction.CommitAsync(); } } }
private async void WriteToStreamButton_Click(object sender, RoutedEventArgs e) { try { rootPage.ResetScenarioOutput(OutputTextBlock); StorageFile file = rootPage.sampleFile; if (file != null) { string userContent = InputTextBox.Text; if (!String.IsNullOrEmpty(userContent)) { using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(transaction.Stream)) { dataWriter.WriteString(userContent); transaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file await transaction.CommitAsync(); OutputTextBlock.Text = "The following text was written to '" + file.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + userContent; } } } else { OutputTextBlock.Text = "The text box is empty, please write something and then click 'Write' again."; } } } catch (FileNotFoundException) { rootPage.NotifyUserFileNotExist(); } }
public static async Task <bool> TryWriteBytesAsync(this StorageFile storageFile, byte[] bytes) { if (bytes == null) { return(false); } try { using (StorageStreamTransaction transaction = await storageFile.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(transaction.Stream)) { dataWriter.WriteBytes(bytes); transaction.Stream.Size = await dataWriter.StoreAsync(); await transaction.CommitAsync(); return(true); } } } catch { return(false); } }
/// <summary> /// 保存 /// </summary> public void storage(string str) { //motify = true; //if (!motify) //{ // return; //} //motify = false; _storage?.Cancel(); _storage = ThreadPool.RunAsync(async(workItemHandler) => { await file_null(); using (StorageStreamTransaction transaction = await _file.OpenTransactedWriteAsync()) { using (DataWriter data_writer = new DataWriter(transaction.Stream)) { data_writer.WriteString(serialization(str)); transaction.Stream.Size = await data_writer.StoreAsync(); await transaction.CommitAsync(); } } }); }
/// <summary> /// 读写 /// </summary> public async Task <string> ce() { string str = "asdsfesrsdfsfse"; file_address = "12data.encryption"; decryption.Add(str); StorageFolder folder = ApplicationData.Current.LocalFolder; try { file = await folder.GetFileAsync(file_address); } catch (FileNotFoundException e) { str = e.ToString(); } //file = await sf.OpenStreamForWriteAsync(); await x_write(); using (Stream filestream = await file.OpenStreamForReadAsync()) { byte[] buff = new byte[1000]; if (filestream.Read(buff, 0, 1000) > 0) { return(Encoding.Unicode.GetString(buff)); } } using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(transaction.Stream)) { dataWriter.WriteString(str); transaction.Stream.Size = await dataWriter.StoreAsync(); await transaction.CommitAsync(); } } using (IRandomAccessStream readstream = await file.OpenAsync(FileAccessMode.Read)) { using (DataReader dataRead = new DataReader(readstream)) { UInt64 size = readstream.Size; UInt32 numBytesLoaded = await dataRead.LoadAsync((UInt32)size); str = dataRead.ReadString(numBytesLoaded); } } if (!string.IsNullOrEmpty(str)) { return(str); } //file = await folder.OpenStreamForWriteAsync(file_address , CreationCollisionOption.OpenIfExists); //await x_write(); return(str); }
public async void rubbish() { //string line = "\r\n"; string usingstr = string.Format("using System;{0}using System.Collections.Generic;{0}using System.Linq;{0}using System.Text;{0}using System.Threading.Tasks;{0}namespace rubbish{1}", line, left); //string classstr = ranstr(); int count; StringBuilder str = new StringBuilder(); for (count = 0; count < 100; count++) { junk.Add(ranstr() + count.ToString()); } str.Append(usingstr); str.Append(constructor()); for (int i = 10; i < junk.Count; i++) { element.Add(lajicontent(junk[i])); } element.Add(content1()); element.Add(content2()); for (int i = 0; i < element.Count;) { count = ran.Next() % element.Count; str.Append(element[count]); element.RemoveAt(count); } for (int i = 10; i < junk.Count; i++) { //temp = string.Format("{0}(o);{1}" , junk[i] , line); //content.Append(temp); str.Append(string.Format("{0}private bool _{1}_bool;{2}", space, junk[i], line)); } for (int i = 10; i < junk.Count; i++) { str.Append(string.Format("{0}private int _{1}_int;{2}", space, junk[i], line)); } str.Append("}\r\n}"); StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(junk[0] + ".cs", CreationCollisionOption.ReplaceExisting); using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(transaction.Stream)) { dataWriter.WriteString(str.ToString()); transaction.Stream.Size = await dataWriter.StoreAsync(); await transaction.CommitAsync(); } } junk.Clear(); str.Clear(); _reminder.Append(file.Path); OnPropertyChanged("reminder"); }
public async Task storage() { if (string.IsNullOrEmpty(text)) { return; } //string str = name + "\n" + text.Replace("\r\n", "\n"); string[] temp = text.Split(new char[] { '\r', '\n' }); StringBuilder str = new StringBuilder(); str.Append(name + "\n\n"); foreach (var t in temp) { if (!string.IsNullOrEmpty(t)) { str.Append(t + "\n\n"); } } if (!_open) { str.Append("http://blog.csdn.net/lindexi_gd"); } using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(transaction.Stream)) { dataWriter.WriteString(str.ToString()); transaction.Stream.Size = await dataWriter.StoreAsync(); await transaction.CommitAsync(); } } if (string.IsNullOrWhiteSpace(name)) { name = "请输入标题"; return; } if (!_open) { file = await file.CopyAsync(folder, name + ".md", NameCollisionOption.GenerateUniqueName); try { StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("text"); System.IO.Directory.Delete(folder.Path); } catch { } _open = true; } reminder = reminder = "保存文件" + file.Path + " " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString(); }
public async Task SaveCookie(string filename, CookieContainer rcookie, Uri uri) { StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFile sampleFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); using (StorageStreamTransaction transaction = await sampleFile.OpenTransactedWriteAsync()) { CookieSerializer.Serialize(rcookie.GetCookies(uri), uri, transaction.Stream.AsStream()); await transaction.CommitAsync(); } }
public async Task <bool> WriteXmlFileAsync <T>(T objectTowWrite) { StorageFile sf; if (!File.Exists(this.ConfigurationFileName)) { string folderName = Path.GetDirectoryName(this.ConfigurationFileName); StorageFolder storeStorageFolder = await StorageFolder.GetFolderFromPathAsync(folderName); sf = await storeStorageFolder.CreateFileAsync(Path.GetFileName(this.ConfigurationFileName), CreationCollisionOption.ReplaceExisting); } else { sf = await StorageFile.GetFileFromPathAsync(this.ConfigurationFileName); } if (sf == null) { this.LastError = string.Format("Could not get the File:{0}", this.ConfigurationFileName); return(false); } try { using (StorageStreamTransaction transaction = await sf.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(transaction.Stream)) { if (WriteXmlToString(objectTowWrite, out string stringToWrite)) { dataWriter.WriteString(stringToWrite); transaction.Stream.Size = await dataWriter.StoreAsync(); await transaction.CommitAsync(); return(true); } else { this.LastError = "Could not wirte Objetct to stream"; return(false); } } } } catch (Exception e) { this.LastError = e.Message; return(false); } }
public async Task save() { using (StorageStreamTransaction storageStreamTransaction = await mpd.SelectedNote.File.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(storageStreamTransaction.Stream)) { mpd.SelectedNote.Content = mpd.CurrentNoteContent; dataWriter.WriteString(mpd.CurrentNoteContent); storageStreamTransaction.Stream.Size = await dataWriter.StoreAsync(); await storageStreamTransaction.CommitAsync(); } } }
public async void LoadPresets() { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as picker.FileTypeFilter.Add(".json"); // Default file name if the user does not type one in or select a file to replace var t_storagefile = await picker.PickSingleFileAsync(); if (t_storagefile == null) { return; } String json_str; using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataReader dataReader = new Windows.Storage.Streams.DataReader(transaction.Stream)) { uint numBytesLoaded = await dataReader.LoadAsync((uint)transaction.Stream.Size); json_str = dataReader.ReadString(numBytesLoaded); await transaction.Stream.FlushAsync(); await transaction.CommitAsync(); } } List <PresetItem> list = null; try { list = (List <PresetItem>)Serial.JsonHelper.FromJson(json_str, m_Presets.GetType()); }catch (Exception e) { return; } if (list == null) { return; } C_PRESETLIST.ItemsSource = null; foreach (PresetItem item in list) { m_Presets.Add(item); } C_PRESETLIST.ItemsSource = m_Presets; }
/// <summary> /// Writes a stream to a file, overwriting any existing data /// </summary> /// <param name="file">The file to write to</param> /// <param name="stream">The content to write to the file</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task which completes when the write operation finishes</returns> public static async Task <bool> WriteStreamAsync(IFile file, Stream stream, CancellationToken cancellationToken) { if (stream == null) { return(false); } if (file == null) { return(false); } bool success = true; StorageFile storageFile = await StorageFile.GetFileFromPathAsync(file.Path); if (file != null) { try { if (stream != null) { using (StorageStreamTransaction transaction = await storageFile.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(transaction.Stream)) { dataWriter.WriteBytes(await ReadFully(stream, cancellationToken)); transaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file await transaction.CommitAsync(); } } } else { //JK.JKTools.JKLog("JK#66# The text box is empty, please write something and then click 'Write' again."); success = false; } } catch (FileNotFoundException) { //JK.JKTools.JKLog("JK#67# NotifyUserFileNotExist()"); success = false; } } else { //JK.JKTools.JKLog("JK#68# NotifyUserFileNotExist()"); success = false; } return(success); }
public IAsyncOperation <bool> DownloadToFileAsync(IRecord record, StorageFile file) { if (file == null) { throw new ArgumentNullException("file"); } return(AsyncInfo.Run(cancelToken => Task.Run(async() => { using ( StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync().AsTask(cancelToken)) { return await DownloadAsync(record, transaction.Stream).AsTask(cancelToken); } }))); }
public static async Task WriteFile(Byte[] data, StorageFile file) { // Wait for file to be free while (IsFileLocked(file)) { await Task.Delay(100); } using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync()) using (DataWriter writer = new DataWriter(transaction.Stream)) { writer.WriteString(Encoding.UTF8.GetString(data)); // reset stream size to override the file transaction.Stream.Size = await writer.StoreAsync(); await transaction.CommitAsync(); } }
private async void WriteToStreamButton_Click(object sender, RoutedEventArgs e) { StorageFile file = rootPage.sampleFile; if (file != null) { try { string userContent = InputTextBox.Text; if (!String.IsNullOrEmpty(userContent)) { using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync()) { using (DataWriter dataWriter = new DataWriter(transaction.Stream)) { dataWriter.WriteString(userContent); transaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file await transaction.CommitAsync(); rootPage.NotifyUser(String.Format("The following text was written to '{0}' using a stream:{1}{2}", file.Name, Environment.NewLine, userContent), NotifyType.StatusMessage); } } } else { rootPage.NotifyUser("The text box is empty, please write something and then click 'Write' again.", NotifyType.ErrorMessage); } } catch (FileNotFoundException) { rootPage.NotifyUserFileNotExist(); } catch (Exception ex) { // I/O errors are reported as exceptions. rootPage.NotifyUser(String.Format("Error writing to '{0}': {1}", file.Name, ex.Message), NotifyType.ErrorMessage); } } else { rootPage.NotifyUserFileNotExist(); } }
private async void C_SAVE_PRESET_BUTTON_Click(object sender, RoutedEventArgs e) { Model.TrickerStarPresetSerialize s = new Model.TrickerStarPresetSerialize(); foreach (var item in m_PresetList) { s.PresetCodes.Add(item); } String json_str = Model.JsonHelper.ToJson(s, s.GetType()); var picker = new Windows.Storage.Pickers.FileSavePicker(); picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as picker.FileTypeChoices.Add("JSON", new List <string>() { ".json" }); // Default file name if the user does not type one in or select a file to replace picker.SuggestedFileName = "NewDocument"; var t_storagefile = await picker.PickSaveFileAsync(); if (t_storagefile == null) { return; } using (StorageStreamTransaction transaction = await t_storagefile.OpenTransactedWriteAsync()) { using (Windows.Storage.Streams.DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(transaction.Stream)) { dataWriter.WriteString(json_str); transaction.Stream.Size = await dataWriter.StoreAsync(); await transaction.Stream.FlushAsync(); await transaction.CommitAsync(); } } }