2016-07-18 40 views
0

我有一个json文件,我可以读/写它。首先,我尝试从资产中读取数据,但这种方式在运行时无法写入。然后我这样做:我在哪里可以把我的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”中?它在哪里?

+0

到根目录下。 –

+0

您可以将文件放入getExternalStorageDirectory(),getFilesDir()和getExternalFilesDir();您也可以提供资产中的文件,然后从资产复制到其中一个目录。 – greenapps

+0

'在“/ storage/sdcard0”? '如果你写了一个文件到那个目录,那么这个文件就在那个目录下。在“/ storage/sdcard0”中。还有什么地方 ?奇怪的问题。 – greenapps

回答

0

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

1

最好的解决办法是捆绑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); 
} 
相关问题