How to store setting with UWP C#? - c#

I a'm running an uwp app on Rasbperry Pi 3 with Windows 10 IoT OS via Visual Studio Remote Machine and Release is selected.
The problem is how to save settings I have made and use the same settings when run same UWP app later.
How is it done? I can read the settings from the text file from
Windows.ApplicationModel.Package.Current.InstalledLocation;
But of course I can't save any changes to the same text file.
Where exactly should I put the text file if I wan't to save changes to text file?
But perhaps I can use this
Windows.Storage.ApplicationData.Current.LocalSettings;
But how do I check if there is no value stored and put instead an default value?
With this I am trying to save these settings it doesn't work.
The point with this is that I can use these same settings when I run the same uwp app again.
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["setting1"] = textBlockDelayValue.Text;
localSettings.Values["setting2"] = checkShow;

Where exactly should I put the text file if I wan't to save changes to
text file?
You can put the text file in Windows.Storage.ApplicationData.Current.LocalFolder of the solution and access it with this piece of code:
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
async void WriteFile()
{
StorageFile sampleFile = await localFolder.CreateFileAsync("test.txt",
CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(sampleFile, "111");
}
async void ReadFile()
{
try
{
StorageFile sampleFile = await localFolder.GetFileAsync("test.txt");
String content = await FileIO.ReadTextAsync(sampleFile);
}
catch (Exception)
{
// Timestamp not found
}
}
But how do I check if there is no value stored and put instead an
default value?
You can read them out like this:
var value1 = ApplicationData.Current.LocalSettings.Values["setting1"];
var value2 = ApplicationData.Current.LocalSettings.Values["setting2"];

Related

MediaSource.CreateFromUri(...) cannot retrieve the file for MediaSource.

Here is my code........
public MediaPlaybackItem GetMediaPlaybackItemFromPath(string path)
{
//StorageFile file = await StorageFile.GetFileFromPathAsync(path);
var source = MediaSource.CreateFromUri(new Uri(path));
return new MediaPlaybackItem(source);
}
If I use this method I cannot play music. But if I try this I can play music.
public async Task<MediaPlaybackItem> GetMediaPlaybackItemFromPathAsync(string path)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path);
var source = MediaSource.CreateFromStorageFile(file);
return new MediaPlaybackItem(source);
}
Whats the problem with this? I am using mediaplaybacklist for MediaPlayer.Source . How can I get proper MediaSource using my first method? Help me please.
You could not pass file path parameter to CreateFromUri directly. In general, the Uri parameter is http protocol address such as http://www.testvideo.com/forkvideo/test.mp4. But we could pass the file path with uwp file access uri scheme.
For example:
Media file stored in the installation folder.
ms-appx:///
Local folder.
ms-appdata:///local/
Temporary folder.
ms-appdata:///temp/
For more you could refer this document.

Acces Denied when I use Open File Picker for open text file for RichEditBox UWP C#

I want to open a text file with Open File Picker and show in a RichEditBox, but when I select the file and push Ok, Visual Studio show "Access Denied", I want to know how to solve this please, there is my code:
var picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
picker.FileTypeFilter.Add("*");
picker.FileTypeFilter.Add(".txt");
picker.FileTypeFilter.Add(".text");
picker.FileTypeFilter.Add(".bat");
picker.FileTypeFilter.Add(".js");
picker.FileTypeFilter.Add(".vbs");
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile filepath = await StorageFile.GetFileFromPathAsync(file.Path);
string text = await FileIO.ReadTextAsync(filepath);
RichEditBox1.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);
}
You don't need to call StorageFile.GetFileFromPathAsync(file.Path) since you already have this StorageFile in the file variable returned from PickSingleFileAsync:
StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
string text = await FileIO.ReadTextAsync(file);
RichEditBox1.Document.SetText(Windows.UI.Text.TextSetOptions.None, text);
}
The unnecessary GetFileFromPathAsync probably throws an AccessDenied error since the FileOpenPicker provides access only through the returned StorageFile and doesn't give direct access to the file through its path. This behavior is version dependent and new versions of Windows 10 will allow more direct access through file system API (see the Build 2017 talk UWP Apps file access improvements

GetFolderFromPathAsync function access denied

I'm making a Windows 10 Universal App and I want the user to pick a folder to save the document files for the App. The path for this folder is saved to ApplicationData.Current.RoamingSettings.Values.
Here's the code:
On first Start:
var folderPicker = new FolderPicker { SuggestedStartLocation = PickerLocationId.ComputerFolder };
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
StorageFolder homeFolder = await folder.CreateFolderAsync("App1 Data", CreationCollisionOption.OpenIfExists);
var save = ApplicationData.Current.RoamingSettings.Values;
save["HomeFolder"] = homeFolder.Path;
When HomeFolder is set:
string dir = save["HomeFolder"].ToString();
try
{
StorageFolder homeFolder = await StorageFolder.GetFolderFromPathAsync(dir);
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
The thrown Exception in the second code sample is:
System.UnauthorizedAccessException: access denied (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
So my question is, how do you use the GetFolderFromPathAsync function correctly?
I checked all strings for the paths, they are all right, even
StorageFolder.GetFolderFromPathAsync(storageFolder.Path);
doesn't work.
Do you know a solution?
Use the StorageFile directly rather than converting to a path.
To store the file returned from the file picker for later use save the StorageFile in the AccessCache classes FutureAccessList or MostRecentlyUsedList. The path doesn't include the spermissions needed to open the file. The StorageFile carries the permissions and grants access to the file.
I discussed this in more detail in my blog entry Skip the path: stick to the StorageFile

Copy file from app installation folder to Local storage

I'm attempting to copy a file from the installed location of my Windows 8 app to it's local storage. I've been researching around and trying to do this to no avail. This is what I have come up with so far but I'm not sure where I'm going wrong.
private async void TransferToStorage()
{
try
{
// Get file from appx install folder
Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;
Windows.Storage.StorageFolder installedLocation = package.InstalledLocation;
StorageFile temp1 = await installedLocation.GetFileAsync("track.xml");
// Read the file
var lines = await FileIO.ReadLinesAsync(temp1);
//Create the file in local storage
StorageFile myStorageFile = await localFolder.CreateFileAsync("track_iso.xml", CreationCollisionOption.ReplaceExisting);
// Write to it
await FileIO.WriteLinesAsync(myStorageFile, lines);
}
catch (Exception)
{
}
}
Any ideas?
Solved it myself. Here is the method for anyone else that encounters this question / problem:
private async void TransferToStorage()
{
// Has the file been copied already?
try
{
await ApplicationData.Current.LocalFolder.GetFileAsync("localfile.xml");
// No exception means it exists
return;
}
catch (System.IO.FileNotFoundException)
{
// The file obviously doesn't exist
}
// Cant await inside catch, but this works anyway
StorageFile stopfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///installfile.xml"));
await stopfile.CopyAsync(ApplicationData.Current.LocalFolder);
}
No reason to read all the lines and write it to another file. Just use File.Copy.

How can I write to a specific location in Windows Phone 8

When I press a button, I want it to overwrite a file to a specific folder.
I use this code:
private void btnArial_Click(object sender, RoutedEventArgs e)
{
string cssDocument = "body{font-family:\"Arial\";}";
//I want to write file style.css to folder css inside html
string path = Package.Current.InstalledLocation.Path + "\\Html\\css\\style.css";
if (File.Exists(path))
{
StreamWriter writer = new StreamWriter(path);
writer.Write(cssDocument);
writer.Close();
}
changeStyle(new FontFamily("Arial"));
}
When I tested on emulator and actual devide, it worked properly.
But when I submit app to store, it got error - the app exits when I press that button.
The install directory (Package.Current.InstalledLocation) is a read-only location. Unfortunately, due to the way that Visual Studio optimizes development-time deployment, it is set to read-write when the app is deployed from VS. That's why you see a difference in behavior after you submit the app to the store.
If you need to modify a file in your install directory, you must first copy it over to a writeable location - eg. your Local folder.
I prefer using Isolated storage in WP8 to write files and it never fails. Also you can use Windows.Storage apis.
private async void MyButton_Click(object sender, RoutedEventArgs e)
{
string cssDocument = "body{font-family:\"Arial\";}";
// using Windows.Storage
StorageFolder folder = ApplicationData.Current.LocalFolder;
folder = await folder.CreateFolderAsync("HTML", CreationCollisionOption.OpenIfExists);
folder = await folder.CreateFolderAsync("CSS", CreationCollisionOption.OpenIfExists);
StorageFile file = await folder.CreateFileAsync("style.css", CreationCollisionOption.ReplaceExisting);
using (var writer = new StreamWriter(await file.OpenStreamForWriteAsync()))
{
writer.Write(cssDocument);
}
// using using System.IO.IsolatedStorage;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!store.DirectoryExists("HTML/CSS"))
store.CreateDirectory("HTML/CSS");
using (var writer = new StreamWriter(store.OpenFile("HTML/CSS/style.css", FileMode.Create)))
{
writer.Write(cssDocument);
}
}
changeStyle(new FontFamily("Arial"));
}
Exactly..
Write the file in Isolated storage. Its easier and pretty straight forward. The files here can be accessed, viewed, modified, removed, replaced in a very clear way. I personally prefer the Isolated Storage.

Categories