繁体   English   中英

如何访问/读取/写入Android设备上内部存储中的Documents文件夹?

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

如何访问Android手机内部存储空间中的公共文档文件夹? 我需要读取和写入可公开访问的文件到Documents文件夹中。

好吧,我自己解决了这个问题:)

它与普通Windows桌面应用程序的操作非常相似:

从Documents文件夹创建和读取文件(在Android设备上):

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

完整样本:

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

不要忘记向androidmanifest.xml添加权限

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

写作的样本

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

阅读样本

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

有了读取外部存储的权限,此代码应该适合您。

var path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDocuments);

var filename = System.IO.Path.Combine(path.ToString(), strFile);

System.IO.FileStream fs = new FileStream(filename, FileMode.Open);

byData = new byte[fs.Length];

fs.Read(byData, 0, (int)fs.Length);
fs.Close();

如果你运行的sdk高于23,android版本高于6,你应该实现对用户的访问请求。 请在链接中找到更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM