Search code examples
c#androidxamarinxamarin.androidxamarin-studio

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


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.


Solution

  • 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();
            }