我可以在哪里放置我的 json 文件

本文关键字:json 文件 我的 在哪里 我可以 | 更新日期: 2023-09-27 17:57:23

我有一个json文件,我应该读/写它。首先,我尝试从资产中读取,但这样我就无法在运行时写入。然后我做了这个:

string path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
string fileName = Path.Combine(path.ToString(), "myFile.json");
if(File.Exist(fileName)){
    //do something
} else {
    File.Create(fileName);
    Path.GetDirectoryName(fileName); //This returns "/storage/sdcard0"
}

但是我应该把我的 json 文件放在哪里?在"/storage/sdcard0"中?它在哪里?

我可以在哪里放置我的 json 文件

最好的解决方案是将myFile.json文件捆绑到资产中,并在应用首次启动时将其复制到可写位置:

以下代码为您提供了一个帮助程序类:

public class FileAccessHelper
    {
        public static string GetLocalFilePath(string filename)
        {
            string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            string o= Path.Combine(path, filename);
            return o;
        }
        public static void CopyAssetFile(string path, string fileName)
        {
            using (var br = new BinaryReader(Application.Context.Assets.Open(fileName)))
            {
                using (var bw = new BinaryWriter(new FileStream(path, FileMode.Create)))
                {
                    byte[] buffer = new byte[2048];
                    int length = 0;
                    while ((length = br.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        bw.Write(buffer, 0, length);
                    }
                }
            }
        }
    }

因此,在主要活动中,您可以像这样使用它:

var path = FileAccessHelper.GetLocalFilePath("myFile.json");
if (File.Exists(path))
{
    CopyDatabase(path, myFile.json);
}

您可以设置断点并检查路径变量的值吗?通过这种方式,您可以获取保存 json 文件的实际路径。