When building WinRT applications there will be the need to create IStorageFiles in the local storage area of your application. In this post I was going to walk through how we can do this step by step.
Step 1: Get the StorageForlder object for your application
var storageFolder = ApplicationData.Current.LocalFolder;
Step 2: Crate the folder you want to put your file into
var userImagesFolder = await CreateFolder(storageFolder, "UserImages" );
// this is the contents of the CreateFolder method
private async Task<StorageFolder> CreateFolder(StorageFolder storageFolder, string folderName)
{
StorageFolder folder = null;
// we do the try w/ empty catch because the GetFolderAsync will throw if not found and we cannot do await inside a catch block
try
{
folder = await storageFolder.GetFolderAsync(folderName);
}
catch { }
if (folder == null)
{
folder = await storageFolder.CreateFolderAsync(folderName);
}
return folder;
}
Step 3: Create the file object
var myImage = await userImagesFolder.CreateFileAsync("FileName.png", CreationCollisionOption.ReplaceExisting);
Step 4: Write content to the file object
// buffer is a pointer of a memory stream of an image
await FileIO.WriteBufferAsync(newGuestSilhouetteImage, buffer);
All the code in one block
public async Task CreateLocalFile()
{
var storageFolder = ApplicationData.Current.LocalFolder;
var userImagesFolder = await CreateFolder(storageFolder, "UserImages" );
var myImage = await userImagesFolder.CreateFileAsync("FileName.png", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBufferAsync(newGuestSilhouetteImage, buffer);
}
private async Task<StorageFolder> CreateFolder(StorageFolder storageFolder, string folderName)
{
StorageFolder folder = null;
// we do the try w/ empty catch because the GetFolderAsync will throw if not found and we cannot do await inside a catch block
try
{
folder = await storageFolder.GetFolderAsync(folderName);
}
catch { }
if (folder == null)
{
folder = await storageFolder.CreateFolderAsync(folderName);
}
return folder;
}
As you can see creating storage files is not much work and is pretty straight forward.
Till next time,
Posted
07-04-2012 2:07 PM
by
Derik Whittaker