Some simple and helpful abstractions for common Filesystem problems
static class FileSystem {
// Returns a path to a directory that can be used to temporarily store data.
// Potentially cleared by the user (eg: on Android in the device settings) or by the OS when space runs low.
static string CacheDirectory { get; }
// Returns a path to a directory that contains app data.
// This directory may not be visible to the user.
static string AppDataDirectory { get; }
// Returns a path to a directory that contains user-visible data.
// This directory may be visible/editable to the user.
static string UserDataDirectory { get; }
// Opens a file Stream to a file embedded in the app package.
// Android: Asset
// iOS: NSBundle.MainBundle
// UWP: Package.InstalledLocation
static Task<Stream> OpenAppPackageFileAsync(string filename);
}
Would this be something that would exist in a nested class under the Platform API:
public class Platform {
public class Directories {
public static string AppData { get; }
}
}
Yeah my first thought was stick it in Platform as well. Can we think of any other interesting bits we might be able to provide related to filesystem?
I removed Roaming as this is not really supported the same way across devices. For example, on iOS the user must have an iCloud account and agree to use it.
This concept of synchronised data should be a separate one. This API is for local-only - even though it is backed up, it is still just for this device.
The design should be validated against UWP, for example ApplicationData.Current.LocalCacheFolder returns a StorageFolder object not a string.
Correct, it would just be the .Path at the end :)
if only it was that easy. If you try the following code:
var tempDirPath = ApplicationData.Current.LocalCacheFolder.Path;
var tempFilePath = Path.Combine(tempDirPath, "test.txt");
File.WriteAllText(tempDirPath, "Hello World!");
The write throws a System.UnauthorizedAccessException. The only way I could get writing temp files to work was using the StorageFolder/StorageFile classes.
Thanks for bringing this up, I will investigate.
Just been retesting this and noticed a typo in the quick test I did yesterday (oops)
var tempDirPath = ApplicationData.Current.LocalCacheFolder.Path;
var tempFilePath = Path.Combine(tempDirPath, "test.txt");
File.WriteAllText(tempFilePath, "Hello World!");
and it now works! Looks like they fixed it in the .NET Std 2.0 update (which is what you are targeting).
So the proposed design should work fine.
Most helpful comment
Just been retesting this and noticed a typo in the quick test I did yesterday (oops)
and it now works! Looks like they fixed it in the .NET Std 2.0 update (which is what you are targeting).
So the proposed design should work fine.