首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >访问外部公用文件夹(文档/下载)

访问外部公用文件夹(文档/下载)
EN

Stack Overflow用户
提问于 2022-11-23 08:17:49
回答 1查看 44关注 0票数 0

我使用的是GetExternalStoragePublicDirectory,但现在不推荐它了,它可以返回标准路径“/存储/模拟/0/下载”,但从Android 12我可以保存,只加载从我的应用程序存储的文件,如果我添加同一个文件重命名的pc是“过滤”和不可访问,它似乎不存在!我从我的应用程序中存储一个txt文件,我如何才能再次访问下载外部公用文件夹?

EN

回答 1

Stack Overflow用户

发布于 2022-11-24 07:28:49

我创建了一个示例来测试GetExternalStoragePublicDirectory方法,并在Download文件夹中创建了一个txt文件。下面是MainActivity的代码:

代码语言:javascript
复制
            Button write = this.FindViewById<Button>(Resource.Id.buttonwrite);
            Button read = this.FindViewById<Button>(Resource.Id.buttonread);
            write.Click += (s, e) =>
            {
                var path = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads);
                var file = Path.Combine(path + "/app.txt");
                using (System.IO.FileStream os = new System.IO.FileStream(file, System.IO.FileMode.OpenOrCreate))
                {
                    string temp = "this is test string";
                    byte[] buffer = Encoding.UTF8.GetBytes(temp);
                    os.Write(buffer, 0, buffer.Length);
                }
                Intent intent = new Intent(DownloadManager.ActionViewDownloads);
                StartActivity(intent);
                // this line code can open the download folder and view all the files in it. When the user click the file, it will be open
            };
            read.Click += (s, e) =>
            {
                var path = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads);
                var file = Path.Combine(path + "/app.txt");
           /*     using (System.IO.FileStream os = new System.IO.FileStream(file, System.IO.FileMode.OpenOrCreate))
                {
                    StreamReader streamReader = new StreamReader(os);
                    var content = streamReader.ReadToEnd();
                } */
                Intent intent = new Intent(Intent.ActionOpenDocument);
                intent.AddCategory(Intent.CategoryOpenable);
                intent.SetType("text/*");
                intent.PutExtra(DocumentsContract.ExtraInitialUri, Uri.Parse(file));
                StartActivityForResult(intent, 2);
                //This code can open the file picker and let the user to choose a file
            };

当我被文件管理器重命名为New.txt时,仍然可以读取New.txt文件。只需将var file = Path.Combine(path + "/app.txt");更改为var file = Path.Combine(path + "/New.txt");并使用/*中的代码即可读取。因此,如果该文件是由您的应用程序创建的,您的应用程序可以访问它,即使该文件已被uesr重命名。但是您可以访问公用文件夹中的文件,该文件不是由应用程序创建的。

此外,如果你不需要把你的应用程序推到谷歌游戏,你可以使用访问所有文件的权限,根据我在this link的旧答案和关于deprecated GetExternalStoragePublicDirectory的答案。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74543630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档