Delen via


Xamarin.Essentials: File System Helpers

The FileSystem class contains a series of helpers to find the application's cache and data directories and open files inside of the app package.

Get started

To start using this API, read the getting started guide for Xamarin.Essentials to ensure the library is properly installed and set up in your projects.

Using File System Helpers

Add a reference to Xamarin.Essentials in your class:

using Xamarin.Essentials;

To get the application's directory to store cache data. Cache data can be used for any data that needs to persist longer than temporary data, but should not be data that is required to properly operate, as the OS dictates when this storage is cleared.

var cacheDir = FileSystem.CacheDirectory;

To get the application's top-level directory for any files that are not user data files. These files are backed up with the operating system syncing framework. See Platform Implementation Specifics below.

var mainDir = FileSystem.AppDataDirectory;

If you would like to open a file that has been bundled into the application package, you can use the OpenAppPackageFileAsync method to read the contents. In the example below a file named mybundledfile.txt has been added to each platform. See the platform implementation specifics section for details.

 var fileName = "mybundledfile.txt";
 using (var stream = await FileSystem.OpenAppPackageFileAsync(fileName))
 {
    using (var reader = new StreamReader(stream))
    {
        var fileContents = await reader.ReadToEndAsync();
    }
 }

Platform Implementation Specifics

  • CacheDirectory – Returns the CacheDir of the current context.
  • AppDataDirectory – Returns the FilesDir of the current context and are backed up using Auto Backup starting on API 23 and above.

Add any file into the Assets folder in the Android project and mark the Build Action as AndroidAsset to use it with OpenAppPackageFileAsync.

API

Find more Xamarin videos on Channel 9 and YouTube.