Friday, 30 January 2015

Local, Roaming & Temporary Files

Previously we looked at storing data in the the local and roaming settings which basically amounted to storing key value pairs in dictionaries, really easy to work with, but limited and not suited for user data, but rather appropriate for settings.

To save real data we should create local files. We can do this in the following manner

async void CreateFile()
{
    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
    StorageFile localFile = await localFolder.CreateFileAsync("MyFile.txt", CreationCollisionOption.GenerateUniqueName);

    await FileIO.WriteTextAsync(localFile, "Hello World");
    var localPath = localFolder.Path;

}

really easy, now I added a localPath variable at the end so that you could create a break point and inspect where you`re file is getting saved to.

let`s take a look, if we navigate to that directory our MyFile.txt will be there.

C:\Users\Administrator\AppData\Local\Packages\bb5297f1-72d9-418c-a1ec-901850673c50_75cr2b68sm664\LocalState

Ok Next let`s try and read our file

async Task<string> ReadFromFile()
{
    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
    StorageFile localFile = await localFolder.GetFileAsync("MyFile.txt");
    return await FileIO.ReadTextAsync(localFile);

}

and that`s it you`re writing and reading to a file, and as before with just changing LocalFolder To RoamingFolder your file is now roaming with your user account.

async void CreateFile()
{
    StorageFolder roamingFolder = ApplicationData.Current.RoamingFolder;
    StorageFile roamingFile = await roamingFolder.CreateFileAsync("MyFile.txt", CreationCollisionOption.GenerateUniqueName);

    await FileIO.WriteTextAsync(roamingFile, "Hello World");
}

async Task<string> ReadFromFile()
{
    StorageFolder roamingFolder = ApplicationData.Current.RoamingFolder;
    StorageFile roamingFile = await roamingFolder.GetFileAsync("MyFile.txt");
    return await FileIO.ReadTextAsync(roamingFile);

}

could it be any easier, I dare to say i think not

and of coarse as promised saving temporary files.

async void CreateFile()
{
    StorageFolder roamingFolder = ApplicationData.Current.TemporaryFolder;
    StorageFile roamingFile = await roamingFolder.CreateFileAsync("MyFile.txt", CreationCollisionOption.GenerateUniqueName);

    await FileIO.WriteTextAsync(roamingFile, "Hello World");
}

async Task<string> ReadFromFile()
{
    StorageFolder roamingFolder = ApplicationData.Current.TemporaryFolder;
    StorageFile roamingFile = await roamingFolder.GetFileAsync("MyFile.txt");
    return await FileIO.ReadTextAsync(roamingFile);

}

just as before