Deleting Files in a Storage Folder Using UWP

Just a little helper method that I used in a recent project to delete files, given a particular name, and excluding a provided list of files:

        internal static async Task DeleteTempFiles(ObservableCollection<StorageFile> exceptionFiles, StorageFolder folder, string fileNameStartsWith)
        {
            var files = (await folder.GetFilesAsync())
                .Where(p => p.DisplayName.StartsWith(fileNameStartsWith)
                && !exceptionFiles.Any(e => e.DisplayName == p.DisplayName));            

            foreach(var file in files)
            {
                await file.DeleteAsync(StorageDeleteOption.Default);                
            }
        }

You can call it like this:

	await FileHelper.DeleteTempFiles(Files, KnownFolders.PicturesLibrary, "_tmpFile");

It will delete all files in the Pictures folder starting with _tmpFile, and exclude anything in the Files collection.

Leave a Reply

Your email address will not be published. Required fields are marked *