简体   繁体   English

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

[英]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? 如何访问Android手机内部存储空间中的公共文档文件夹? I need to read and write publicly-accessible files into the Documents folder. 我需要读取和写入可公开访问的文件到Documents文件夹中。

Well I have solved this myself :) 好吧,我自己解决了这个问题:)

It's pretty much the same as you would do it for a normal Windows Desktop application: 它与普通Windows桌面应用程序的操作非常相似:

Create and read file from Documents folder (on an Android device): 从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;
        }
    }
}

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

don't forget to add permission to androidmanifest.xml 不要忘记向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();
        }

With permissions to read external storage, this code should work for you. 有了读取外部存储的权限,此代码应该适合您。

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

if you are running on sdk higher than 23, android version higher than 6, you should implement access request to user. 如果你运行的sdk高于23,android版本高于6,你应该实现对用户的访问请求。 please find more information here on this link 请在链接中找到更多信息

暂无
暂无

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

相关问题 我可以从txt文件内部存储空间(“文档”文件夹中读取和写入),但是无法浏览到该位置,因为它不存在 - I can read and write from a txt file internal storage (documents folder) but cannot browse to that location because it doesn't exist 如何访问文档文件夹(UWP) - How do I gain access to the documents folder (UWP) 如何访问“文档和设置”文件夹? - How can I access the "Documents and Settings" folder? 如何从 xmarine android c# App 中的 Internal Storage Custom 文件夹显示 pdf? - how to show pdf from Internal Storage Custom folder in xmarine android c# App? 如何将一个TXT文件从Assets文件夹复制到SD /内部存储Android C#Xamarin - How to copy one TXT File from Assets folder to SD / Internal Storage Android C# Xamarin Xamarin Android,从内部存储/下载中读取一个简单的文本文件 - Xamarin Android, read a simple text file from internal storage/Download 如何从Visual Studio中开发的Android C#应用程序访问SoftLayer对象存储。 - How do I access SoftLayer object storage from a C# application for Android, developed in Visual Studio. 如何使用 Unity 从 android 内部存储访问图像和 3D object ZD7EFA19FBE7D3972FD5ADB6024223D74 - How to access Images and 3D object from android internal Storage using Unity C# 如何在项目浏览器中的“读取,写入”中访问文本文件,该文件不在Windows Phone 7的独立存储中? - How can I access a text file in the project explorer “read, write” which is not in the isolated storage in Windows Phone 7? 如何使用 Blazored 在 Blazor 服务器端读取和写入本地存储? - How do I read and write to the local storage in Blazor server side using Blazored?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM