How to create a file when the file is not exist in

2019-08-06 03:08发布

问题:

What I want
open a file if it exists, create it if it not exists

What I code

        try
        {
            return await folder.GetFileAsync(fileName);

        }
        catch (FileNotFoundException )
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName);
            return file;
        }

What the error
Cannot await in the body of a catch clause

How to make it?

回答1:

Why not just call CreateFileAsync and specify OpenIfExists?

Create the new file or folder with the desired name, or returns an existing item if a file or folder already exists with that name.



回答2:

Well if you do not want to change the code much. You can set a flag exceptionOccurred = true in catch flag and then write the code to create the file after the catch clause if the flag is true.