How do I access/read from/write to Documents folder in Internal Storage on Android devices?

19,777

Solution 1

don't forget to add permission to androidmanifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>    

sample of writing

        // write on SD card file data in the text box
        try {
            File myFile = new File("/sdcard/mysdfile.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = 
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(txtData.getText());
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),
                    "Done writing SD 'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

sample of reading

         try {
            File myFile = new File("/sdcard/mysdfile.txt");
            FileInputStream fIn = new FileInputStream(myFile);
            BufferedReader myReader = new BufferedReader(
                    new InputStreamReader(fIn));
            String aDataRow = "";
            String aBuffer = "";
            while ((aDataRow = myReader.readLine()) != null) {
                aBuffer += aDataRow + "\n";
            }
            txtData.setText(aBuffer);
            myReader.close();
            Toast.makeText(getBaseContext(),
                    "Done reading SD 'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

Solution 2

Well I have solved this myself :)

It's pretty much the same as you would do it for a normal Windows Desktop application:

Create and read file from Documents folder (on an Android device):

string content = "Jason rules";
string filename = "file.txt";

var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
if (!Directory.Exists(documents))
{
    Console.WriteLine("Directory does not exist.");
}
else
{
    Console.WriteLine("Directory exists.");

    File.WriteAllText(documents + @"/" + filename, content);

    if (!File.Exists(documents + @"/" + filename))
    {
        Console.WriteLine("Document not found.");
    }
    else
    {
        string newContent = File.ReadAllText(documents + @"/" + filename);

        TextView viewer = FindViewById<TextView>(Resource.Id.textView1);
        if (viewer != null)
        {
            viewer.Text = newContent;
        }
    }
}

Complete Sample:

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);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.button);

            if (button != null)
            {
                button.Click += delegate
                {
                        button.Enabled = false;

                        string content = "Jason rules";
                        string filename = "file.txt";

                        var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
                        if (!Directory.Exists(documents))
                        {
                            Console.WriteLine("Directory does not exist.");
                        }
                        else
                        {
                            Console.WriteLine("Directory exists.");

                            File.WriteAllText(documents + @"/" + filename, content);

                            if (!File.Exists(documents + @"/" + filename))
                            {
                                Console.WriteLine("Document not found.");
                            }
                            else
                            {
                                string newContent = File.ReadAllText(documents + @"/" + filename);

                                TextView viewer = FindViewById<TextView>(Resource.Id.textView1);
                                if (viewer != null)
                                {
                                    viewer.Text = newContent;
                                }
                            }
                        }
                };
            }
        }
    }
}
Share:
19,777
jay_t55
Author by

jay_t55

Updated on July 24, 2022

Comments

  • jay_t55
    jay_t55 almost 2 years

    How do I access public Documents folder on an Android phone's internal storage? I need to read and write publicly-accessible files into the Documents folder.

  • jay_t55
    jay_t55 over 9 years
    To get the sample working, just throw a button and textView in there and name the button 'button'.
  • jay_t55
    jay_t55 over 9 years
    Hi :) Thanks for your answer. I am wondering, does this write the file to the external SD card or the phone's inbuilt card? I ask this because not everybody has an external card slot and not everybody has an external card or even uses them.
  • phpniki
    phpniki over 9 years
    please approve the answer ;)
  • Ugur
    Ugur over 7 years
    Is that only for SDCard?
  • Inrego
    Inrego about 5 years
    This doesn't seem to be the public documents folder. System.Environment.GetFolderPath(System.Environment.SpecialF‌​older.MyDocuments) returns /data/user/0/{appId}/files/
  • IamSierraCharlie
    IamSierraCharlie over 4 years
    Where do I put this? I get "Error CS0103 The name 'Android' does not exist in the current context"
  • Taşyürek Gökşah
    Taşyürek Gökşah over 4 years
    To Android Project. You can't reach to Android.OS.Environment from shared lib. Bye the way GetExternalStoragePublicDirectory return Java.IO.File type. Not the path to combine.
  • bertasoft
    bertasoft almost 4 years
    this is deprecated in Android 11