/// <summary> /// Loads file from path /// </summary> /// <param name="filepath">path to a file</param> /// <param name="folder">folder or null (to load from application folder)</param> /// <returns></returns> protected XDocument LoadFile(string filepath, StorageFolder folder) { try { StorageFile file; //load file if (folder == null) { var uri = new Uri(filepath); file = StorageFile.GetFileFromApplicationUriAsync(uri).AsTask().ConfigureAwait(false).GetAwaiter().GetResult(); } else { file = folder.GetFileAsync(filepath).AsTask().ConfigureAwait(false).GetAwaiter().GetResult(); } //parse and return var result = FileIO.ReadTextAsync(file).AsTask().ConfigureAwait(false).GetAwaiter().GetResult(); return XDocument.Parse(result); } catch { return null; } }
public async Task< string> GetCachedUserPreference() { roamingFolder = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile file = await roamingFolder.GetFileAsync(filename); string response = await FileIO.ReadTextAsync(file); return response; }
public async Task<string> loadTextFile(StorageFolder folder, string key = null) { StorageFile myFile; try { if (key == null) { myFile = await folder.GetFileAsync("myData.txt"); } else { myFile = await folder.GetFileAsync(key + ".txt"); } } catch { myFile = null; } string text = ""; if (myFile != null) { text = await FileIO.ReadTextAsync(myFile); } return text; }
private async void InitSettings() { StorageFile settingsFile; string json; try { settingsFile = await _localFolder.GetFileAsync("settings.json"); //Getting Text files } catch (Exception e) { ProfileTextBox.Text = new StringBuilder(ProfileTextBox.Text) .Append("settings exception: " + e.Message + "\n") .ToString(); // there is no settings file // create one _settings = new Settings(); settingsFile = await UpdateSettingsFileAsync(); } json = await FileIO.ReadTextAsync(settingsFile); ProfileTextBox.Text = new StringBuilder(ProfileTextBox.Text) .Append("read settings:" + json + "\n") .ToString(); _settings = JsonConvert.DeserializeObject <Settings>(json); valueThreshold.Text = "" + _settings.rotateThreshold; automaticSwitch.IsChecked = _settings.automaticSwitchBetweenProfiles; }
public async void LoadLocalSettings() { if (composite == null) { composite = new Windows.Storage.ApplicationDataCompositeValue(); } else { try { currentCurrencyCode = (string)composite["currentCurrencyCode"]; currentDate = (string)composite["currentDate"]; currentDateSelection = (int)composite["currentDateSelection"]; toRateHistoryDate = (DateTimeOffset?)composite["toRateHistoryDate"]; fromRateHistoryDate = (DateTimeOffset?)composite["fromRateHistoryDate"]; } catch (Exception e) { Debug.WriteLine(e.StackTrace); } } try { StorageFile datesFile = await localFolder.GetFileAsync("dates.txt"); String datesString = await FileIO.ReadTextAsync(datesFile); Debug.WriteLine(datesString); dates = JsonConvert.DeserializeObject <List <YearRates> >(datesString); } catch (Exception) { Debug.WriteLine("No dates saved"); } try { StorageFile ratesFile = await localFolder.GetFileAsync("rates.txt"); String ratesString = await FileIO.ReadTextAsync(ratesFile); rates = JsonConvert.DeserializeObject <List <Rate> >(ratesString); } catch (Exception) { Debug.WriteLine("No rates saved"); } try { StorageFile historyFile = await localFolder.GetFileAsync("history.txt"); String historyOfCurrencyString = await FileIO.ReadTextAsync(historyFile); historyOfCurrency = JsonConvert.DeserializeObject <List <DayRate> >(historyOfCurrencyString); } catch (Exception) { Debug.WriteLine("No history saved"); } }
//Initialize the new Crypto object (initialized only once per app startup) public async void initCrypto() { this.strAsymmetricAlgName = AsymmetricAlgorithmNames.RsaPkcs1; this.asymmetricKeyLength = 512; //Checks SecureChat's folder if a key pair already exists and set keyPairExists boolean Windows.Storage.StorageFolder localAppFolder = Windows.Storage.ApplicationData.Current.LocalFolder; string cryptoFilePrivate = "SecureChatPrivateKeys.sckey"; //STORED AS BYTE DATA string cryptoFilePublic = "SecureChatPublicKey.sckey"; //STORED AS TEXT DATA if ((await localAppFolder.TryGetItemAsync(cryptoFilePublic) != null) && (await localAppFolder.TryGetItemAsync(cryptoFilePrivate) != null)) { this.keyPairExists = true; } else { this.keyPairExists = false; } //Load Keys depending on keyPairExists value if (this.keyPairExists == true) { //DIRECT IBUFFER //StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync(cryptoFilePublic); //this.buffPublicKey = await FileIO.ReadBufferAsync(loadedCryptoFilePublic); //FROM BYTE //StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync("BytePubKey.sckey"); //this.buffPublicKey = await FileIO.ReadBufferAsync(loadedCryptoFilePublic); //Open Public Key File. Convert key from STRING to BYTE and then convert to IBUFFER StorageFile loadedCryptoFilePublic = await localAppFolder.GetFileAsync(cryptoFilePublic); String publicKeyStringVersion = await FileIO.ReadTextAsync(loadedCryptoFilePublic); this.publicKeyByteVersion = Convert.FromBase64String(publicKeyStringVersion); this.buffPublicKey = this.publicKeyByteVersion.AsBuffer(); //Open Private Key File StorageFile loadedCryptoFilePrivate = await localAppFolder.GetFileAsync(cryptoFilePrivate); this.buffPrivateKeyStorage = await FileIO.ReadBufferAsync(loadedCryptoFilePrivate); } else { //Generate new key pair CryptographicKey temp = this.CreateAsymmetricKeyPair(strAsymmetricAlgName, asymmetricKeyLength, out buffPublicKey, out buffPrivateKeyStorage); //Convert public key from IBUFFER type to BYTE type. Convert from BYTE type to STRING type WindowsRuntimeBufferExtensions.CopyTo(this.buffPublicKey, this.publicKeyByteVersion); string publicKeyStringVersion = Convert.ToBase64String(this.publicKeyByteVersion); //Store keys in appropriate files (Public as PLAIN TEXT, Private as IBUFFER) await FileIO.WriteTextAsync((await localAppFolder.CreateFileAsync(cryptoFilePublic)), publicKeyStringVersion); await FileIO.WriteBufferAsync((await localAppFolder.CreateFileAsync(cryptoFilePrivate)), this.buffPrivateKeyStorage); } }
private async void LoadFavorites() { FavouritesList = new List <FavouritesJSON>(); string filepath = @"Assets\Favorites.json"; StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation; StorageFile file = await folder.GetFileAsync(filepath); // error here var JSONData = "e"; try { if ((bool)localSettings.Values["FirstFavRun"] == true) { localSettings.Values["FirstFavRun"] = false; StorageFile sfile = await localFolder.CreateFileAsync("Favorites.json", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(sfile, JSONData); JSONData = await Windows.Storage.FileIO.ReadTextAsync(file); } else { localSettings.Values["FirstFavRun"] = false; StorageFile ssfile = await localFolder.GetFileAsync("Favorites.json"); JSONData = await FileIO.ReadTextAsync(ssfile); } } catch { localSettings.Values["FirstFavRun"] = false; StorageFile sssfile = await localFolder.CreateFileAsync("Favorites.json", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(sssfile, JSONData); JSONData = await Windows.Storage.FileIO.ReadTextAsync(file); } localSettings.Values["FirstFavRun"] = false; StorageFile sampleFile = await localFolder.CreateFileAsync("Favorites.json", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(sampleFile, JSONData); FavouritesClass FavouritesListJSON = JsonConvert.DeserializeObject <FavouritesClass>(JSONData); foreach (var item in FavouritesListJSON.Websites) { FavouritesList.Add(new FavouritesJSON() { HeaderJSON = item.HeaderJSON, UrlJSON = item.UrlJSON, FavIconJSON = item.FavIconJSON, }); } Favorites.ItemsSource = FavouritesList; }
async void ReadData() { Windows.Storage.StorageFolder roamingFolder = Windows.Storage.ApplicationData.Current.RoamingFolder; try { StorageFile file11 = await roamingFolder.GetFileAsync("doc1_name.txt"); ph11 = await FileIO.ReadTextAsync(file11); txt_block_1.Text = ph11; StorageFile file12 = await roamingFolder.GetFileAsync("doc1_phone.txt"); ph12 = await FileIO.ReadTextAsync(file12); StorageFile file13 = await roamingFolder.GetFileAsync("doc1_des.txt"); ph13 = await FileIO.ReadTextAsync(file13); txt_block_12.Text = ph13; StorageFile file21 = await roamingFolder.GetFileAsync("doc2_name.txt"); ph21 = await FileIO.ReadTextAsync(file21); txt_block_2.Text = ph21; StorageFile file22 = await roamingFolder.GetFileAsync("doc2_phone.txt"); ph22 = await FileIO.ReadTextAsync(file22); StorageFile file23 = await roamingFolder.GetFileAsync("doc2_des.txt"); ph23 = await FileIO.ReadTextAsync(file23); txt_block_22.Text = ph23; StorageFile file31 = await roamingFolder.GetFileAsync("doc3_name.txt"); ph31 = await FileIO.ReadTextAsync(file31); txt_block_3.Text = ph31; StorageFile file32 = await roamingFolder.GetFileAsync("doc3_phone.txt"); ph32 = await FileIO.ReadTextAsync(file32); StorageFile file33 = await roamingFolder.GetFileAsync("doc3_des.txt"); ph33 = await FileIO.ReadTextAsync(file33); txt_block_32.Text = ph33; } catch (Exception) { } }
private async void DemoDataPersistenceCodeThroughFiles() { StorageFile localFileToWrite = await localFolder.CreateFileAsync("FileTest.txt", CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(localFileToWrite, "This is a sample file!"); StorageFile localFileToRead = await localFolder.GetFileAsync("FileTest.txt"); string textRead = await FileIO.ReadTextAsync(localFileToRead); StorageFile localFileToDelete = await localFolder.GetFileAsync("FileTest.txt"); await localFileToDelete.DeleteAsync(); }
private async void PlayButton_Click(object sender, RoutedEventArgs e) { Song clickedOnSong = ((Button)sender).DataContext as Song; if (clickedOnSong.IsPaused) { clickedOnSong.IsPaused = false; } else { Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets"); Windows.Storage.StorageFile audioFile = await folder.GetFileAsync(clickedOnSong.AudioFile); player.AutoPlay = false; player.Source = MediaSource.CreateFromStorageFile(audioFile); } var buttons = ((StackPanel)((AppBarButton)sender).Parent).Children; foreach (var button in buttons) { if (((AppBarButton)button).Name == "Play") { ((AppBarButton)button).Visibility = Visibility.Collapsed; } else { ((AppBarButton)button).Visibility = Visibility.Visible; } } clickedOnSong.IsPlaying = true; player.Play(); }
private async void ReadFile_Click_1(object sender, RoutedEventArgs e) { string fileName = SelectedFile.Text; if (fileName.Length < 1) { ("Error: You have not selected a file.").Show(); return; } Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync(fileName); // string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile); string atext = ""; var buffer = await Windows.Storage.FileIO.ReadBufferAsync(sampleFile); using (var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer)) { atext = dataReader.ReadString(buffer.Length); } FileContents.Text = atext; }
private async void SaveText_Click(object sender, RoutedEventArgs e) { string textToWrite = TextForFile.Text.ToString(); if (textToWrite.Length < 1) { ("Error: Nothing to write to the file.").Show(); return; } string fileName = SelectedFile.Text; if (fileName.Length < 1) { ("Error: You have not selected a file.").Show(); return; } Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync(fileName); await Windows.Storage.FileIO.WriteTextAsync(sampleFile, textToWrite); ("File saved").Show(); }
public async void LoadPreviousCurrenciesToListForChart() { var list = new List <Rate>(); try { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("sampleChart.json"); var text = await FileIO.ReadTextAsync(sampleFile); list = JsonConvert.DeserializeObject <List <Rate> >(text); this.viewModel2.ItemsChart = list; //Load list to datatable and chart DataTable dt = GetDataTable(); FillDataGrid(dt, this.dataGridCurrency); dataGridCurrency.ItemsSource = dt.DefaultView; GetChartData(this.viewModel2.ItemsChart); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
private async void UploadButton_Click(object sender, RoutedEventArgs e) { //do whatever you need. Canvas.SetZIndex(UploadGrid, 3); Canvas.SetZIndex(GoalGrid, 1); Canvas.SetZIndex(MapGrid, 1); Page_Title.Text = "Upload"; Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; try { Windows.Storage.StorageFile saveFile = await storageFolder.GetFileAsync("save.png"); var bitmap = new BitmapImage(new Uri(saveFile.Path)); var Stream = await saveFile.OpenAsync(Windows.Storage.FileAccessMode.Read); bitmap.SetSource(Stream); img.Source = bitmap; } catch (Exception) { } }
public async Task <Google.Apis.Drive.v2.Data.File> UploadFile(string uploadFileName, string contentType, Action <IUploadProgress> uploadProgressEventHandler = null, Action <Google.Apis.Drive.v2.Data.File> responseReceivedEventHandler = null)//上傳檔案 { Windows.Storage.StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.GetFileAsync(uploadFileName); IRandomAccessStream readStream = await file.OpenReadAsync(); Stream uploadStream = readStream.AsStream(); string title = uploadFileName; this.CheckCredentialTimeStamp(); Google.Apis.Drive.v2.Data.File fileToInsert = new Google.Apis.Drive.v2.Data.File { Title = title }; FilesResource.InsertMediaUpload insertRequest = _service.Files.Insert(fileToInsert, uploadStream, contentType); insertRequest.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize * DOUBLE; AddUploadEventHandler(uploadProgressEventHandler, responseReceivedEventHandler, insertRequest); try { insertRequest.Upload(); } catch (Exception exception) { throw exception; } finally { uploadStream.Dispose(); } return(insertRequest.ResponseBody); }
private async void AddFile(object sender, RoutedEventArgs e) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("sample.txt"); }
/// <summary> /// 创建并获取当前文件(临时文件夹) /// </summary> /// <param name="FileName"></param> /// <returns></returns> public async Task <Windows.Storage.StorageFile> CreatFile(string FileName) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.TemporaryFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync(FileName, Windows.Storage.CreationCollisionOption.ReplaceExisting); return(await storageFolder.GetFileAsync(FileName)); }
public async void Load(string fileName) { var list = new List <CurrencyView>(); // Check if we had previously Save information of our friends // previously try { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("sample.json"); var text = await FileIO.ReadTextAsync(sampleFile); list = JsonConvert.DeserializeObject <List <CurrencyView> >(text); this.ViewModel.Items = list; System.Diagnostics.Debug.WriteLine("Wielkosc listy: " + list.Count); DataTable dt = GetDataTable(); FillDataGrid(dt, this.dataGrid); dataGrid.ItemsSource = dt.DefaultView; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
private async void Submit_Click(object sender, RoutedEventArgs e) { String fileName = "Details.txt"; String name = Name.Text + Environment.NewLine; String email = Email.Text + Environment.NewLine; String address = Address.Text + Environment.NewLine; Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("Details.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting); Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile file = await localFolder.GetFileAsync(fileName); await FileIO.WriteTextAsync(file, name); // await FileIO.AppendTextAsync(file, name); await FileIO.AppendTextAsync(file, email); await FileIO.AppendTextAsync(file, address); Frame.Navigate(typeof(TicketSent)); }
public async void LoadSettings() { try { /* * Uri uri = new System.Uri("ms-appx:///trustbase.cfg"); * StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri); * string contents = await FileIO.ReadTextAsync(file); * //*/ Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; StorageFile configFile = await storageFolder.GetFileAsync("trustbase.cfg"); string contents = await FileIO.ReadTextAsync(configFile); configuration.Load(contents); LoadAddons(configuration); LoadPlugins(configuration); LoadAggregation(configuration); SyncPluginsWithAggregation(); DebugModify.IsEnabled = false; //this.ConfigurationSettingsGridView.ItemsSource = pluginList; } catch (Exception) { Debug.WriteLine("And you failed : :'("); } }
/// <summary> /// Gets File located in Local Storage, /// Input file name may include folder paths seperated by "\\". /// Example: filename = "Documentation\\Tutorial\\US\\ENG\\version.txt" /// </summary> /// <param name="filename">Name of file with full path.</param> /// <param name="rootFolder">Parental folder.</param> /// <returns>Target StorageFile.</returns> public async Task<StorageFile> GetFileAsync(string filename, StorageFolder rootFolder = null) { if (string.IsNullOrEmpty(filename)) { return null; } var semaphore = GetSemaphore(filename); await semaphore.WaitAsync(); try { rootFolder = rootFolder ?? AntaresBaseFolder.Instance.RoamingFolder; return await rootFolder.GetFileAsync(NormalizePath(filename)); } catch (Exception ex) { LogManager.Instance.LogException(ex.ToString()); return null; } finally { semaphore.Release(); } }
/// <summary> /// Erstellt eine Backup-Datei der aktuellen JSON Datei /// </summary> /// <returns></returns> private async Task CreateBackupJSONAsync() { StorageFile storageFile = await _jsonFileTarget.GetFileAsync("jobStorage.json"); await storageFile.CopyAsync(_tempFolder, _backupFileName, NameCollisionOption.ReplaceExisting); }
private async void exportData_Click(object sender, RoutedEventArgs e) { Windows.ApplicationModel.Email.EmailMessage emailMessage = new Windows.ApplicationModel.Email.EmailMessage(); emailMessage.To.Add(new Windows.ApplicationModel.Email.EmailRecipient("*****@*****.**")); string messageBody = "Exported DATA - accelerometer"; emailMessage.Body = messageBody; string DataFile = @"Assets\storage.txt"; Windows.Storage.StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; Windows.Storage.StorageFile attachmentFile = await storageFolder.GetFileAsync(DataFile); if (attachmentFile != null) { var stream = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(attachmentFile); var attachment = new Windows.ApplicationModel.Email.EmailAttachment( attachmentFile.Name, stream); emailMessage.Attachments.Add(attachment); } await Windows.ApplicationModel.Email.EmailManager.ShowComposeNewEmailAsync(emailMessage); /* * IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication(); * //create new file * using (StreamWriter SW = new StreamWriter(new IsolatedStorageFileStream("Info.txt", FileMode.Create, FileAccess.Write, ISF))) * { * string text = "Hi this is the text which will be written to the file and we can retrieve that later"; * SW.WriteLine(text); * SW.Close(); * MessageBox.Show("text has been saved successfully to the file"); * } * * StorageFolder newFolder = KnownFolders.DocumentsLibrary; * StorageFile file = await newFolder.CreateFileAsync("export.txt", CreationCollisionOption.ReplaceExisting); * * string ReadedData = await FileIO.ReadTextAsync(file); * await FileIO.WriteTextAsync(file,ReadedData); */ /* * FileSavePicker savePicker = new FileSavePicker(); * * savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; * savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" }); * savePicker.SuggestedFileName = "export_accelerometer"; * * Windows.Storage.StorageFile file = await savePicker.PickSaveFileAndContinue(); * if (file != null) * { * string DataFile = @"Assets\storage.txt"; * Windows.Storage.StorageFolder storageFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; * Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync(DataFile); * Windows.Storage.CachedFileManager.DeferUpdates(sampleFile); * await Windows.Storage.FileIO.WriteTextAsync(sampleFile, sampleFile.Name); * Windows.Storage.Provider.FileUpdateStatus status = * await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(sampleFile); * } */ }
private async void Buttonfilepick_Click(object sender, RoutedEventArgs e) { // GamePlay gp = new GamePlay(); FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { textblockoutput.Text = "Selected File:" + file.Path; var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var image = new BitmapImage(); image.SetSource(stream); imageview.Source = image; } else { textblockoutput.Text = "Try Again.."; } Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets"); Windows.Storage.StorageFile file1 = await folder.GetFileAsync("soundEffect.mp3"); player.AutoPlay = false; player.Source = MediaSource.CreateFromStorageFile(file); player.Play(); }
public async static Task SaveFileToLocal(string fileName, string token) { Windows.Storage.StorageFolder newFolder = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFolderAsync(token); Windows.Storage.StorageFile newFile = await newFolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting); Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalCacheFolder; Windows.Storage.StorageFile tragetFile = await storageFolder.GetFileAsync(fileName); var buffer = await Windows.Storage.FileIO.ReadBufferAsync(tragetFile); await Windows.Storage.FileIO.WriteBufferAsync(newFile, buffer); #region ReadWriteStream //string contentText = null; //using (var stream = await tragetFile.OpenAsync(Windows.Storage.FileAccessMode.Read)) //{ // ulong size = stream.Size; // var inputStream = stream.GetInputStreamAt(0); // var dataReader = new Windows.Storage.Streams.DataReader(inputStream); // uint numBytesLoaded = await dataReader.LoadAsync((uint)size); // contentText = dataReader.ReadString(numBytesLoaded); //} //using (var stream = await newFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) //{ // var outputStream = stream.GetOutputStreamAt(0); // var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream); // dataWriter.WriteString(contentText); // await dataWriter.StoreAsync(); // await outputStream.FlushAsync(); //} #endregion }
public async Task openAutoSave() { try { Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; IReadOnlyList <StorageFile> dirFiles = await localFolder.GetFilesAsync(); if (dirFiles != null) { if (dirFiles.Count > 0) { String name = dirFiles.Last().Name; StorageFile last = await localFolder.GetFileAsync(name); // Process input if the user clicked OK. if (last != null) { await filemanager.ReadFile(last.Path, last); GlobalNodeHandler.viewNode = GlobalNodeHandler.masterNode; GlobalNodeHandler.viewNode.UpdateViewRepresentation(); } } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Could not open AutoSave: Message:" + e.Message); } }
public async Task autoSaveMap() { try { String now = DateTime.Now.ToString("yyyyMMddHHmmssfff"); Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder; if (localFolder != null) { IReadOnlyList <StorageFile> dirFiles = await localFolder.GetFilesAsync(); if (dirFiles != null) { if (dirFiles.Count > maxAutoSaves) { String filename = dirFiles.First().Name; StorageFile firstfile = await localFolder.GetFileAsync(filename); await firstfile.DeleteAsync(); } } String name = "Autosave" + now + ".ppm"; Windows.Storage.StorageFile file = await localFolder.CreateFileAsync(name); filemanager.WriteFile(path, file); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Autosave failed: Message:" + e.Message); } }
/// <summary> /// Saves /// </summary> /// <param name="errorMessage"></param> public async static void SaveError(string errorMessage) { string newCaseStart = $"\r\nDate: {DateTime.Now.ToShortDateString()}\r\n "; const string caseEnd = "\r\n- - -"; Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile errorLog; //Check for existing file if (File.Exists(storageFolder.Path + "/InfoScreen-ErrorLog.txt")) { //Select file errorLog = await storageFolder.GetFileAsync("InfoScreen-ErrorLog.txt"); //Add to file await FileIO.AppendTextAsync(errorLog, $"{newCaseStart} {errorMessage} {caseEnd}"); } else { //Create or replace existing file. errorLog = await storageFolder.CreateFileAsync("InfoScreen-ErrorLog.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting); await FileIO.WriteTextAsync(errorLog, $"" + newCaseStart + errorMessage + caseEnd); } }
/// <summary> /// 向AppData中的rtf文本中写入string /// </summary> /// <param name="fileName">AppData目录下的文件名,需要带拓展名</param> /// <param name="content">要写入的内容</param> /// <param name="tag">要选择的模式</param> /// <returns>文本信息</returns> public async Task SetStringToFile(string fileName, string content, int tag) { //ExportFile Service Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; // Dropdown of file types the user can save the file as savePicker.FileTypeChoices.Add("Rich Text", new List <string>() { ".rtf" }); // Default file name if the user does not type one in or select a file to replace savePicker.SuggestedFileName = "New Document"; Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile file; if (tag == 1) { file = await storageFolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting); } else { file = await storageFolder.GetFileAsync(fileName); } if (file != null) { System.IO.File.WriteAllText(file.Path, content); await new Windows.UI.Popups.MessageDialog("添加成功").ShowAsync(); } }
private async void writeFile(String name, String text) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sample = await storageFolder.GetFileAsync(name + ".txt"); await Windows.Storage.FileIO.WriteTextAsync(sample, text); }
async void WriteCookies() { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile settingFile = await storageFolder.GetFileAsync("setting.ini"); await Windows.Storage.FileIO.WriteTextAsync(settingFile, cookies_text.Text); }
/// <summary> /// Deletes the changelog. /// </summary> public static async void DeleteChangelog() { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile file = await storageFolder.GetFileAsync("Changelog.txt"); await file.DeleteAsync(StorageDeleteOption.Default); }
//private async void ReadFileToken() //{ // Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; // Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("Token.txt"); // currentToken.token = await Windows.Storage.FileIO.ReadTextAsync(sampleFile); //} #region Void CreatedFileToken() private async Task CreatedFileToken() { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("Token.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting); sampleFile = await storageFolder.GetFileAsync("Token.txt"); await Windows.Storage.FileIO.WriteTextAsync(sampleFile, currentToken.token); }
public static async void WriteLocalFile(string jsonString) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("pueblosmagicos.txt"); await Windows.Storage.FileIO.WriteTextAsync(sampleFile, jsonString); }
/// <summary> /// Check to see if the file exists or not /// </summary> /// <param name="storagefolder">StorageFolder</param> /// <param name="filename">string</param> /// <returns>StorageFile or null</returns> public static async Task<StorageFile> ValidateFile(StorageFolder storagefolder, string filename) { try { return await storagefolder.GetFileAsync(filename); } catch (FileNotFoundException) { return null; } }
//------------------------------------------------------------------------------- #region +[static]copyToLocal 選択フォルダからローカルへコピー //------------------------------------------------------------------------------- // public async static void copyToLocal(StorageFolder rootDir, Action<int, int, int, int> progressReportFunc = null) { var localDir = Windows.Storage.ApplicationData.Current.LocalFolder; var dataDir_dst = await localDir.CreateFolderAsync(DATA_FOLDER_NAME, CreationCollisionOption.OpenIfExists); var dataDir_src = await rootDir.GetFolderAsync("CDATA"); var fileList = await dataDir_src.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.DefaultQuery); if (progressReportFunc != null) { progressReportFunc(0, 2, 0, fileList.Count); } int count = 0; foreach (var file in fileList) { await file.CopyAsync(dataDir_dst, file.Name, NameCollisionOption.ReplaceExisting); count++; if (progressReportFunc != null) { progressReportFunc(0, 2, count, fileList.Count); } } var imageDir = await localDir.CreateFolderAsync(IMAGES_FOLDER_NAME, CreationCollisionOption.OpenIfExists); var imgFile = await rootDir.GetFileAsync("C084CUTL.CCZ"); MemoryStream ms = new MemoryStream(); using (Stream stream = (await imgFile.OpenReadAsync()).AsStream()) { byte[] buf = new byte[0x10000000]; while (true) { int r = stream.Read(buf, 0, buf.Length); if (r <= 0) { break; } ms.Write(buf, 0, r); } } var zipArchive = new ZipArchive(ms); if (progressReportFunc != null) { progressReportFunc(1, 2, 0, zipArchive.Entries.Count); } count = 0; foreach (var entry in zipArchive.Entries) { string name = entry.Name; using (Stream dstStr = await imageDir.OpenStreamForWriteAsync(name, CreationCollisionOption.ReplaceExisting)) using (Stream srcStr = entry.Open()) { int size; const int BUF_SIZE = 0x100000; byte[] buf = new byte[BUF_SIZE]; size = srcStr.Read(buf, 0, BUF_SIZE); while (size > 0) { dstStr.Write(buf, 0, size); size = srcStr.Read(buf, 0, BUF_SIZE); } count++; if (progressReportFunc != null) { progressReportFunc(1, 2, count, zipArchive.Entries.Count); } } } if (progressReportFunc != null) { progressReportFunc(2, 2, count, zipArchive.Entries.Count); } ms.Dispose(); zipArchive.Dispose(); }
// Working /// <summary> /// Gets a file from the file system. /// </summary> /// <param name="folder">The folder that contains the file.</param> /// <param name="fileName">Name of the file.</param> /// <returns>The file if it exists, null otherwise.</returns> public static StorageFile GetFile(StorageFolder folder, string fileName) { try { return folder.GetFileAsync(fileName).AsTask().Result; } catch (Exception) { return null; } }
internal async static Task CopyNecessaryFilesFromCurrentPackage(StorageFile diffManifestFile, StorageFolder currentPackageFolder, StorageFolder newPackageFolder) { await FileUtils.MergeFolders(currentPackageFolder, newPackageFolder); JObject diffManifest = await CodePushUtils.GetJObjectFromFile(diffManifestFile); var deletedFiles = (JArray)diffManifest["deletedFiles"]; foreach (string fileNameToDelete in deletedFiles) { StorageFile fileToDelete = await newPackageFolder.GetFileAsync(fileNameToDelete); await fileToDelete.DeleteAsync(); } }
public static async Task<bool> Launch(string filename, StorageFolder folder) { IStorageFile file = await folder.GetFileAsync(filename); LauncherOptions options = new LauncherOptions(); //options.DisplayApplicationPicker = true; //options.FallbackUri = GetUri(cole_protocol); bool result = await Launcher.LaunchFileAsync(file, options); return result; }
//public static async Task<bool> fileExistAsync(StorageFolder folder, string fileName) public static async Task<bool> fileExistAsync(StorageFolder folder, string fileName) { try { await folder.GetFileAsync(fileName); return true; } catch( Exception e ) { return false; } }
private static bool FileExists(StorageFolder folder, string fileName) { try { var task = folder.GetFileAsync(fileName).AsTask(); task.Wait(); return true; } catch { return false; } }
public static async Task<bool> DoesFileExistAsync(StorageFile file, StorageFolder folder, string fileName) { try { file = await folder.GetFileAsync(fileName); return true; } catch { return false; } }
public static async Task<bool> DoesFileExistAsync(StorageFolder folder, string filename) { var folders = (await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFoldersAsync()).ToList(); try { await folder.GetFileAsync(filename); return true; } catch { return false; } }
public async void Setup() { Folder = ApplicationData.Current.LocalFolder; //połącz do pliku jesli istnieje try { File = await Folder.GetFileAsync("json.txt"); } //utwórz gdy go nie ma catch { File = await Folder.CreateFileAsync("json.txt"); } }
/// <summary> /// Checks if a file exists into the <see cref="StorageFolder"/> /// </summary> /// <param name="storageFolder">the folder where the function has to check</param> /// <param name="fileName">the name of the file</param> /// <returns>true if the file exists, false otherwise</returns> public async Task<bool> IsFileExists(StorageFolder storageFolder, string fileName) { using (await InstanceLock.LockAsync()) { try { fileName = fileName.Replace("/", "\\"); var file = await storageFolder.GetFileAsync(fileName); return (file != null); } catch { return false; } } }
private static async Task<Album> CreateAlbum(StorageFolder albumFolder) { var rgx = new Regex(@"(.*) \[([0-9]*)\] - (.*)"); var match = rgx.Match(albumFolder.Name); var songfiles = (await albumFolder.GetFilesAsync()).Where(f => f.FileType != ".jpg"); var coverfile = await albumFolder.GetFileAsync("Cover.jpg"); return new Album { Id = albumFolder.Path, Artist = match.Groups[1].Value, Year = int.Parse(match.Groups[2].Value), Name = match.Groups[3].Value, CoverArt = new Uri(coverfile.Path), Songs = await Task.WhenAll(songfiles.Select(CreateSong)) }; }
public async Task MoveFileAsync(StorageFile file, StorageFolder destinationFolder, string desiredNewFileName) { if (Exist(destinationFolder, desiredNewFileName)) { try { StorageFile fileToDelete = await destinationFolder.GetFileAsync(desiredNewFileName); await DeleteAsync(fileToDelete); } catch (Exception) { //TODO there is a known issue of the .net api; fix this when the api will be fixed } } await file.MoveAsync(destinationFolder,desiredNewFileName); }
public static async Task<bool> FileExistsAsync(StorageFolder storageFolder, string fileName) { await LockAsync(); try { try { StorageFile storageFile = await storageFolder.GetFileAsync(fileName); return true; } catch (FileNotFoundException) { return false; } } finally { Unlock(); } }
public static async Task<string> ReadFromFile( string fileName, StorageFolder folder = null) { folder = folder ?? ApplicationData.Current.LocalFolder; var file = await folder.GetFileAsync(fileName); using (var fs = await file.OpenAsync(FileAccessMode.Read)) { using (var inStream = fs.GetInputStreamAt(0)) { using (var reader = new DataReader(inStream)) { await reader.LoadAsync((uint)fs.Size); string data = reader.ReadString((uint)fs.Size); reader.DetachStream(); return data; } } } }
/// <summary> /// check file system /// </summary> /// <param name="rootFolder"></param> private async Task checkFileSystem(StorageFolder rootFolder) { try { StorageFile metaFile = await rootFolder.GetFileAsync(CoreDriver.META_DATA); StorageFolder mdFolder = await rootFolder.GetFolderAsync( MasterDataManagement.MASTER_DATA_FOLDER); StorageFolder transFolder = await rootFolder.GetFolderAsync( TransactionDataManagement.TRANSACTION_DATA_FOLDER); IReadOnlyList<StorageFile> files = await mdFolder.GetFilesAsync(); Assert.AreEqual(Enum.GetValues(typeof(MasterDataType)).Length, files.Count); files = await transFolder.GetFilesAsync(); Assert.AreEqual(1, files.Count); } catch (Exception e) { Assert.Fail(e.ToString()); } }
// This is a private method, and does not require synchronization. We assume caller is // already holding the lock. private static async Task<StorageFile> GetOrCreateFileAsync(StorageFolder storageFolder, string fileName) { StorageFile storageFile = null; try { Debug.WriteLine("File location: {0}", storageFolder.Path); storageFile = await storageFolder.GetFileAsync(fileName); } catch (FileNotFoundException) { Debug.WriteLine("File not found: {0}", fileName); } if (storageFile == null) { storageFile = await storageFolder.CreateFileAsync(fileName); } return storageFile; }
public static async Task UnZip(StorageFolder SourceFolder, string ZipName, StorageFolder DestinationFolder) { var files = new List<StorageFile>(); // open zip var destination = DestinationFolder; var deployedZip = await SourceFolder.GetFileAsync(ZipName); var zipFile = await deployedZip.CopyAsync(DestinationFolder); // Must be in folder with full rights!! using (var zipStream = await zipFile.OpenStreamForReadAsync()) { using (var archive = new ZipArchive(zipStream)) { var entries = archive.Entries; // iterate through zipped objects foreach (var archiveEntry in entries) { await UnzipZipArchiveEntryAsync(archiveEntry, archiveEntry.FullName, destination); } } } await zipFile.DeleteAsync(StorageDeleteOption.PermanentDelete); //cleanup }
public static void SetDB(StorageFolder folder, string dbName, SqliteOption sqliteOption, Action creationDelegate) { bool createIfNotExists = (sqliteOption & SqliteOption.CreateIfNotExists) != 0; bool createAlways = (sqliteOption & SqliteOption.CreateAlways) != 0; bool exists = FileExists(folder,dbName); if (createAlways && exists) { exists = false; var task = folder.GetFileAsync(dbName).AsTask(); task.Wait(); task.Result.DeleteAsync().AsTask().Wait(); } SetDB(new CSDataProviderSqliteWP8("uri=file://" + Path.Combine(folder.Path,dbName)), DEFAULT_CONTEXTNAME); if (!exists && (createIfNotExists || createAlways) && creationDelegate != null) creationDelegate(); }
public static async Task<StorageFile> GetSavedFileAsync(string filename, StorageFolder folder = null) { if (folder == null) folder = ApplicationData.Current.LocalFolder; StorageFile file = null; try { file = await folder.GetFileAsync(filename); } catch (Exception e) { if (e is FileNotFoundException) { AppEventSource.Log.Debug("Suspension: Previously saved file not found. "); } else App.NotifyUser(typeof(SuspensionManager), "Failed the access file.\n" + e.Message); } return file; }
public async static void DeleteFile(StorageFolder folder, string filename) { var file = await folder.GetFileAsync(filename); await file.DeleteAsync(); }
public static async Task<string> ReadFrom(string filename, StorageFolder folder) { StorageFile file = await folder.GetFileAsync(filename); return await FileIO.LoadText(file); }
public static async Task WriteTo(string filename, StorageFolder folder, string content) { StorageFile file = await folder.GetFileAsync(filename); await FileIO.SaveText(file, content); }
private async Task<bool> CheckFileExist(StorageFolder folder, string fileName) { try { var files = await folder.GetFileAsync(fileName); return true; } catch (FileNotFoundException) { return false; } }
public static async Task<IStorageFile> GetFile(string filename, StorageFolder folder) { IStorageFile file = await folder.GetFileAsync(filename); return file; }
async Task<StorageFile> GetStorageFileFromPathList(StorageFolder sf, List<string> filepath) { if (sf == null || filepath == null) return null; bool getFileCrawler = true; while (getFileCrawler || filepath.Count > 1) { sf = await sf.GetFolderAsync(filepath.FirstOrDefault<string>()); if (sf != null) { filepath.RemoveAt(0); } else { getFileCrawler = false; } } if (sf != null && filepath.Count == 1) { return await sf.GetFileAsync(filepath.FirstOrDefault<string>()); } return null; }