0

According to this reference https://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Files can be saved and accessed privately, i.e. no other app or user has access, by using the flag Context.MODE_PRIVATE when opening the filestream.

How can I achieve the same under Xamarin / C#

There seem to be plenty of examples which get the path from Environment.SpecialFolder.Personal

string path = Environment.GetFolderPath (Environment.SpecialFolder.Personal);

But I cannot see any documentation which states that this data is private to the app. In fact there are plenty of anecdotal posts which suggest that it is the same enum as SpecialFolder.MyDocuments.

Can anyone advise how I can write to internal storage which is private to the App.

Many thanks

Mukesh M
  • 2,242
  • 6
  • 28
  • 41
MHugh
  • 455
  • 1
  • 7
  • 20

1 Answers1

1

Can anyone advise how I can write to internal storage which is private to the App.

You can use the following C# codes to write to internal storage:

string FILENAME = "hello_file";
string str = "hello world!";

using (var fos = OpenFileOutput(FILENAME, FileCreationMode.Private))
{
     //get the byte array
     byte[] bytes = Encoding.ASCII.GetBytes(str);
     fos.Write(bytes, 0, bytes.Length);
}

Update: You can use the following codes to read the content back:

using (var ios = OpenFileInput(FILENAME))
{
    string strs;
    using (InputStreamReader sr = new InputStreamReader(ios))
    {
        using (BufferedReader br = new BufferedReader(sr))
        {
            StringBuilder sb = new StringBuilder();
            string line;
            while ((line = br.ReadLine()) != null)
            {
                sb.Append(line);
            }
            strs = sb.ToString();
        }
    }
}
Elvis Xia - MSFT
  • 10,801
  • 1
  • 13
  • 24
  • Thank you for replying to this. My writing executes OK, but when I read back using Context c = Android.App.Application.Context; Stream fis = c.OpenFileInput(FILENAME); ,I get the error Java.IO.FileNotFoundException # – MHugh May 01 '17 at 08:59
  • I've updated the answer to add the codes of reading the file. Please have a check. – Elvis Xia - MSFT May 01 '17 at 09:16