Search code examples
c#filewindows-10-universalstoragefolder

Differences between "DeleteAsync" and "File.Delete" and why "DeleteAsync" doesn't remove file?


Wondering why "DeleteAsync" doesn't delete file but "File.Delete" will do it. Can someone explain this to me? At first I think that the file is open but if the file is open "File.Delete" shouldn't delete it also or...?

private static async void FILESYSTEM_RemoveVideoPosterIfExist(string posterFileNameOnStorage)
{
    IStorageItem videoPosterIStorageItem = await ApplicationData.Current.LocalFolder.TryGetItemAsync(SYSTEM_UserVideoPosterFolder + @"\" + DATABASE_SelectedUserInformation.UserName + "." + SYSTEM_UserPosterFolderExtension + @"\" + posterFileNameOnStorage);
    if (videoPosterIStorageItem != null)
    {
        try
        {
            //Why this doesn't delete file...
            await videoPosterIStorageItem.DeleteAsync(StorageDeleteOption.PermanentDelete);
        }
        catch
        {
            //But this one will delete file.
            StorageFolder applicationStorageFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(SYSTEM_UserVideoPosterFolder + @"\" + DATABASE_SelectedUserInformation.UserName + "." + SYSTEM_UserPosterFolderExtension + @"\");
            File.Delete(applicationStorageFolder.Path + @"\" + posterFileNameOnStorage);
        }
    }
}

Solution

  • The reason is likely to be that there is no native function to delete a file asynchronously. The managed APIs generally are wrappers around the unmanaged ones.

    Take a look at this

    Why isn't there an asynchronous file delete in .net?

     FileInfo fi = new FileInfo(fileName);
     await fi.DeleteAsync(); // C# 5
     fi.DeleteAsync().Wait(); // C# 4
    

    Hope this helps!!