Generating a Temporary Filename in Windows 10 Universal App

December 11, 2015

It appears that the functionality to create a temporary file was omitted from Windows 8 / 10

If anyone knows this to not be the case then please add a comment to that effect.

Consequently, I decided to create a little helper method:



        public static async Task<StorageFile> CreateTempFile(
                 StorageFolder folder, string extension)
        {
            string fileName = string.Empty;

            while (true)
            {
                // Get a random filename
                fileName = string.Format("{0}.{1}", 
                     Guid.NewGuid().ToString(), extension);

                // Check if it already exists
                IReadOnlyList<StorageFile> fileList =
                    await folder.GetFilesAsync();

                // If it does then loop until we have a unique one
                if (!fileList.Any(f => f.DisplayName == fileName)) break;
            }

            var newFile = await folder.CreateFileAsync(fileName);
            return newFile;
        }



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024