gpt4 book ai didi

c# - 如何在 Android 设备上访问/读取/写入内部存储中的文档文件夹?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:38:05 25 4
gpt4 key购买 nike

如何访问 Android 手机内部存储上的公共(public)文档文件夹?我需要在 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;
}
}
}
};
}
}
}
}

关于c# - 如何在 Android 设备上访问/读取/写入内部存储中的文档文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27396592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com