fileioxamarin.androidexternalwritetofile

Xamarin.Android: Write something into a file and be able to open it with the computer afterwards


I am trying to write some kind of an external config file for my Xamarin.Android-application. Just .txt and this only needs to contain several strings, so no rocket science^^

e.g. (Sample Goal/Hopefully final content of the text file:)

[TestSection]
test=12345

I tried it with a tutorial and the following code:

//This code snippet is one example of writing a string to a UTF-8 text file and into the internal storage directory of an application:
public void SaveSomethingIntoExternalTextFile(string toWrite)
{
    var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "config.txt");
    using (var writer = System.IO.File.CreateText(backingFile))
    {
        writer.WriteLine(toWrite);
    }
}

But unfortunately this has no effect. As my only app-specific path is

Phone\Android\data\com.<company_name>.<application_name>\files

I cannot find any file there after running the code above. And even if I create a new file with the computer in the given path, name it as written (config.txt) and run the given code again, still nothing happens (so the string which's passed as parameter into the method unfortunately isn't written into that file as tried).

Just for the sake of completeness, my test application is pretty simple:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    SaveSomethingIntoExternalTextFile("[TestSection]");
    SaveSomethingIntoExternalTextFile("test="+12345);
}

Can anyone maybe help? What am I doing wrong?

Would be really happy about every answer, thanks in advance and

Best regards

P.S.: If I open the by computer generated text file, even if in the file directory its displayed correctly, the heading of the file says config[1].txt, opening again config[2].txt and so on. Or does that not matter/has nothing to do with my attempt above?


Solution

  • If you use System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), the path is like

    /data/data/App3.App3/files/config.txt

    It means that you save it in internal storage, you could not see it without root permission,if you want to see it, you can save it in external storage.

     public void SaveSomethingIntoExternalTextFile(string toWrite)
        {
    
            string path = Android.App.Application.Context.GetExternalFilesDir(null).ToString();
            string filepath = Path.Combine(path, "text.txt");
            using (var writer = System.IO.File.CreateText(filepath))
            {
                writer.WriteLine(toWrite);
            }
        }
    

    The path like :

    /storage/emulated/0/Android/data/App3.App3/files/text.txt