Issue
I'm new to xamarin and i want to write some data to a json file from a simple button_clicked event.
Here's my code: `
JObject jsontry = new JObject(
new JProperty("newprop", "true"));
File.WriteAllText(@"c:\mafirst.json", jsontry.ToString());//this line gives the error
// write JSON directly to a file
using (StreamWriter file = File.CreateText(@"c:\Users\Flora\Desktop\mafirst.json"))//this line gives the same error as well
using (JsonTextWriter writer = new JsonTextWriter(file))
{
jsontry.WriteTo(writer);
}
`
Error: System.UnauthorizedAccessException: 'Access to the path 'c:\mafirst.json' is denied.'
I tried different paths, writing same code in the same project but different .cs files, basically i have tried every idea that comes to my mind and the solutions from the net but nothing works.
Edit:
Sorry for the lack of information about the app. This app is just a learning project for me. I run this code in just the UWP app so i treated it like a UWP app which is logical i guess(?) and thats the only reason that i use a path like (C:\Desktop\blabla.bla).
I run the visual studio with admin privileges and that doesn't seem to work, i just want to write and store some data from my UWP app's C# codes to a JSON file in the local.
Thanks for help.
Solution
Xamarin apps run in a “sandbox”: apps can access very little unless they have the rights and they can only write to and read in folders that are created for your app (so that apps cannot mess with the files/data of other apps).
For file storage inside the sandbox of your app check out (for example):
https://docs.microsoft.com/en-us/xamarin/android/platform/files/
You can write files inside the folder of which the path is given by (for example):
System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData)
The path that is returned is different on Windows, Android and iOS. The most important thing: you can acces it.
Note that there are several Environment.SpecialFolder
enum values you can choose.
For a file path, you could for example use:
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "somefile.txt");
I have used Environment.SpecialFolder.LocalApplicationData
a lot in a shared project for UWP and Android.
Answered By - SymboLinker
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.