我使用的是GetExternalStoragePublicDirectory,但现在不推荐它了,它可以返回标准路径“/存储/模拟/0/下载”,但从Android 12我可以保存,只加载从我的应用程序存储的文件,如果我添加同一个文件重命名的pc是“过滤”和不可访问,它似乎不存在!我从我的应用程序中存储一个txt文件,我如何才能再次访问下载外部公用文件夹?
发布于 2022-11-24 07:28:49
我创建了一个示例来测试GetExternalStoragePublicDirectory方法,并在Download文件夹中创建了一个txt文件。下面是MainActivity的代码:
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的答案。
https://stackoverflow.com/questions/74543630
复制相似问题