如何在设置中保存图像位置

时间:2017-01-12 19:45:53

标签: c# uwp

我在c#/ xaml中开发了一个uwp应用程序。 在我的应用程序中,我使用此代码选择图片文件夹中的图像,并将图像放在网格的背景上:

FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation =  PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".png");

StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
     var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
     var image = new BitmapImage();
     ImageBrush ib = new ImageBrush();
     ib.ImageSource = image;
     image.SetSource(stream);
    set.Background = new ImageBrush { ImageSource = image, Stretch = Stretch.UniformToFill };
}
else
{
     //
}

我想要做的是:将图像位置保存在应用程序设置中以供以后重复使用 我不知道该怎么做......

2 个答案:

答案 0 :(得分:2)

不要在UWP中保存文件路径 - 该应用程序还需要权限,而不仅仅是文件位置。直接从路径获取文件时,您可能会收到 UnauthorizedAccessException - 例如C:\Images\image.jpg

UWP中有两个列表可以记住 StorageItems ,还有权限:FutureAccessListMostRecentlyUsedList

当您将项目添加到此类列表时,您将获得一个令牌,这是您应该记住 LocalSettings 中的内容(例如)。然后,您可以重用此类令牌来访问文件/文件夹。样品:

StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
    // to save the token for further access
    ApplicationData.Current.LocalSettings.Values["MyToken"] = StorageApplicationPermissions.FutureAccessList.Add(file);
    // rest of the code
}

// to get the file later:
StorageFile theFile = await StorageApplicationPermissions.FutureAccessList.GetFileAsync((string)ApplicationData.Current.LocalSettings.Values["MyToken"]);

答案 1 :(得分:1)

您可以通过以下方式使用Windows.Storage.ApplicationDataContainer

var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;

localSettings.Values["some key"] = "your value"; // Store value in settings
var valueFromSettings = localSettings.Values["some key"]; // Getting value from settings

这样您就可以存储和检索文件路径,以获取路径:

var filePath = file.Path;

并从路径中获取StorageFile

var file = await StorageFile.GetFileFromPathAsync(filePath);
相关问题