如何在UWP中使用共享数据

本文关键字:共享 数据 UWP | 更新日期: 2024-09-25 23:43:28

我试图从本地文件夹中的json文件加载数据,它在PC中运行良好,因为数据保存在PC的LocalState文件夹中,但当我尝试在手机中使用它时,它说数据不在手机中。我应该把json文件放在哪里,这样手机和电脑都可以访问它?这是一个UWP应用程序。

如何在UWP中使用共享数据

正如Romasz所说,如果不需要即时同步和100%的数据一致性,请使用漫游数据作为共享数据。

您可以使用漫游数据在一个Microsoft帐户的设备之间存储共享用户数据。这里有一些代码你可以参考:

ApplicationDataContainer roamingSettings = ApplicationData.Current.RoamingSettings;
StorageFolder roamingFolder = ApplicationData.Current.RoamingFolder;
//Get from roaming settings
object userName = roamingSettings.Values["UserName"];
if (userName != null && !string.IsNullOrWhiteSpace(userName.ToString()))
{
    ViewModel.UserName = userName.ToString();
}
//Set to roaming settings
roamingSettings.Values["UserName"] = ViewModel.UserName;
//You can also save the info into a file.
StorageFile processFile = await roamingFolder.CreateFileAsync(processFileName, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(processFile, ViewModel.GameProcess.ToString());
//Get from the file
try
{
    StorageFile processFile = await roamingFolder.GetFileAsync(processFileName);
    string process = await FileIO.ReadTextAsync(processFile);
    int gameProcess;
    if (process != null && int.TryParse(process.ToString(), out gameProcess) && gameProcess > 0)
    {
        ViewModel.GameProcess = gameProcess;
    }
}
catch { }

要获得完整的项目,请访问示例:如何在Win10 UWP应用程序中跨多个设备共享数据。