uSeRnAmEhAhAhAhAhA
uSeRnAmEhAhAhAhAhA

Reputation: 2587

How to correctly use GetFolderAsync()?

In my Windows Store apps, I have always used:

StorageFolder folder = await KnownFolders.DocumentsLibrary.GetFolderAsync("Folder Name");
if(folder != null)
{
    // Folder exists. Open it and load any existing files.
    IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();

    // We now have the files. Do something with them.
}
else
{
    // Folder does not exist. Create it.
    folder.CreateFolderAsync("Folder Name", CreationCollisionOption.OpenIfExists);
}

But just now, I thought, why can't I do it this way?

StorageFolder folder = await KnownFolders.DocumentsLibrary.CreateFolderAsync("Folder Name", CreationCollisionOption.OpenIfExists);

IReadOnlyList<StorageFile> files = await folder.GetFilesAsync();

if(files != null)
{
    // We now have the files. Do something with them.
}

To the best of my knowledge, the first block of code I wrote is the "standard" way - or more commonly-seen way of doing it. But since the second way also works, I am now unsure of which one to use. They both work, but is there any reason why I should not do it the second way?

Upvotes: 1

Views: 2952

Answers (1)

Kumar
Kumar

Reputation: 864

The second block of code works better, Why...?

Give a try with out having folder in Documents Library.

await KnownFolders.DocumentsLibrary.CreateFolderAsync("Folder Name", CreationCollisionOption.OpenIfExists);

The CreationCollisionOption.OpenIfExists will create a specific folder if not exist.

And in first block of code the line which is in else block will never call.

folder.CreateFolderAsync("Folder Name", CreationCollisionOption.OpenIfExists);

If suppose you don't have a folder which is trying to open it will raise a exception System.IO.FileNotFoundException

...

http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.creationcollisionoption.ASPx

Upvotes: 3

Related Questions