I would like to open a file, and if it does not exist create it, similar to this question
The catch is that if the file was newly created I perform some additional initialization logic.
I can use
await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists)
to open the file if it already exists, but how can I tell if the result of this operation was a newly created file or just opening an existing file? Is there a best practice here or am I stuck looking at the file create date or file size?
Ideally the code would look something like this:
var file = await folder.CreateFileAsync(fileName, CreationCollsionOption.OpenIfExists);
//How can I reliably tell if the file was new?
if (fileIsNew)
await InitializeFile(file);
With using the
CreationCollsionOption.OpenIfExiststhere is no way to tell what’s happened other than looking theCreatedDateor theSizeof the file.So I think you are better if you use the
GetFileAsync(like in the linked question) and do your initilaize logic in thecatch FileNotFoundExceptionbranch, because there is no File.Exists in WinRtHowever there is a third solution where you enumerate the files in the directory and check for existence by hand:
Note: in this case potentially you have to prepare to handle race conditions becase it can happen while you are processing the file list somebody creates the file before you (that’s why there is no
File.Existsmethod exists)