【问题标题】:Which Environment.SpecialFolder.XXX will give me Context.getFilesDir()?哪个 Environment.SpecialFolder.XXX 会给我 Context.getFilesDir()?
【发布时间】:2018-11-08 11:56:56
【问题描述】:

我想访问一个文件夹,我可以在其中保存临时文件并在其中写入文件,并且我不需要写入该文件夹的权限。

我目前使用:

string targetBaseDir = Environment.GetFolderPath(
    Environment.SpecialFolder.Personal,
    Environment.SpecialFolderOption.Create
    );

这给了我一个我不需要权限的私有目录,它是对应于Context.getFilesDir() 的目录,但是由于我不需要永久存在该文件,如果我可以将它们保存在目录中会更干净对应于Context.getFilesDir()。我必须写什么而不是.Personal 才能获取目录?

【问题讨论】:

标签: xamarin xamarin.forms xamarin.android


【解决方案1】:

您可以在 .NetStd 库中通过 Xamarin.Essentials 使用 FileSystem.AppDataDirectory 来获取 Android 上的“getFilesDir()”位置。

示例:

var appData = Xamarin.Essentials.FileSystem.AppDataDirectory;

appData 等于 /data/user/0/com.sushihangover.FormsTestSuite/files

还有安卓FilesDir

Log.Debug("SO", FilesDir.ToString() );

等于/data/user/0/com.sushihangover.FormsTestSuite/files

访问可以保存临时文件的文件夹

在这种情况下使用缓存目录:

var cacheDir = Xamarin.Essentials.FileSystem.CacheDirectory;

cacheDir 等于:`/data/user/0/com.sushihangover.FormsTestSuite/cache

回复:https://docs.microsoft.com/en-us/xamarin/essentials/

【讨论】:

    【解决方案2】:

    Environment.SpecialFolder.PersonalEnvironment.SpecialFolder.MyDocuments 都会为您提供Context.getFilesDir() 的路径。

    不过,如果你想保存个临时文件,你可以使用缓存目录Context.getCacheDir()

    虽然缓存目录没有特殊的文件夹枚举。您必须从当前上下文 Context.CacheDir.Path 获取路径,如果使用 Xamarin.Essentials API,则从 Xamarin.Essentials.FileSystem.CacheDirectory 获取路径。

    阅读更多:
    File access with Xamarin.Android with SpecialFolder
    Writing cache file in internal storage
    File system helpers in Xamarin.Essentials

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多