Alright so I've managed to read/write files programatically in C# in Xamarin Studio. And it's working on my device.
However, when I output the exact path that the file is being written to, to the console, that path doesn't even exist anywhere in the entire phone!!!!
How is that?
using System;
using System.IO;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace ToolbarSample
{
[Activity(Label = "ToolbarSample", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
string content = "Jason rules";
string filename = "file.txt";
var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.button);
TextView viewer = FindViewById<TextView>(Resource.Id.textView1);
if (File.Exists(documents + @"/" + filename))
{
string newContent = File.ReadAllText(documents + @"/" + filename);
if (viewer != null)
{
viewer.Text = newContent;
Console.WriteLine("File exists in: " + documents + @"/" + filename);
}
}
if (button != null)
{
button.Click += delegate
{
button.Enabled = false;
if (!Directory.Exists(documents))
{
viewer.Text = "Directory not found: " + documents;
}
else
{
Console.WriteLine("Directory exists.");
File.WriteAllText(documents + @"/" + filename, content);
if (!File.Exists(documents + @"/" + filename))
{
viewer.Text = "File not found: " + documents + @"/" + filename;
}
else
{
string newContent = File.ReadAllText(documents + @"/" + filename);
if (viewer != null)
{
viewer.Text = newContent;
Console.WriteLine("File exists in: " + documents + @"/" + filename);
}
}
}
};
}
}
}
}
The following gets outputted to the console upon successful read from internal sdcard:
Directory exists. File exists in: /data/data/ToolbarSample.ToolbarSample/files/file.txt
But using (many different) file managers - all with root access - and hidden files being shown - I cannot navigate to that path because it does not exist. I even did a whole phone search for "file.txt" and not a single result showed up. Yet I am able to read that file whenever I open my app and click the button.
The file at the location you have specified does exist. You cannot access that location from your PC via USB and File Explorer, but you can access the location (and the file) if you use a good File Manager app like Root Explorer.
If you really want your users to be able to access these saved files, I'd suggest that you save these files to a better location so that the user can easily transfer files from their phone to the computer via USB.