Search code examples
c#uwplockscreen

UWP set lock screen image isn't working


I am trying to set the lock screen background from my app. I'm using the following code:

var cachedPhotos = (await Photos.GetCachedPhotosAsync()).ToList();    // Get a list of Photo objects ({ "id": "12345.jpg", "url": "http://me.com/12345.jpg" }.
var newPhotos = (await Photos.GetAllPhotosAsync()).ToList();    // Ditto above comment.
var newPhotosList = ListHelpers.Merge(cachedPhotos, newPhotos);    // Merge the two lists.
await Photos.CachePhotosAsync(newPhotosList);    // Create a JSON file with a list of Photo objects. Also download each photo into the "photo_cache" folder.
var index = _random.Next(0, newPhotosList.Count - 1);
var photo = newPhotosList[index];

var file = await StorageFile.GetFileFromPathAsync($"{ApplicationData.Current.LocalCacheFolder.Path}\\photo_cache\\{photo.Id}");

if (await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(file))
    Debug.WriteLine("Wallpaper set!");
else
    Debug.WriteLine("Wallpaper failed to set...");

The photo exists and is valid if I view it in File Explorer. My C# is getting the StorageFile correctly. But whenever I run TrySetLockScreenImageAsync it returns false. (Note that it only returns false, and not an Exception or anything that I can actually see what the problem is.) I'm using exactly what I found here, but I just can't get it to work. Is there another piece to this that I'm missing?


Solution

  • Ok so for some weird reason it seems that I have to do a CopyAsync on the StorageFile and copy it to LocalFolder, then use the newly copied file. Apparently it doesn't like the file coming from LocalCacheFolder.