如何在UWP中使用共享数据

时间:2016-04-16 04:08:06

标签: c# json win-universal-app

我尝试从本地文件夹中的json文件加载数据并且它在PC中正常工作,因为数据保存在PC的LocalState文件夹中但是当我尝试在手机中使用它时它说数据不是在电话里。我应该在哪里保留json文件,以便手机和PC都可以访问它?这是一个UWP应用程序。

2 个答案:

答案 0 :(得分:0)

与Romasz说的一样,如果您不需要即时同步和100%数据一致,请使用Roaming data作为共享数据。

答案 1 :(得分:0)

您可以使用漫游数据在一个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 { }

要获得完整项目,请转到Sample:How to share data across multiple devices in Win10 UWP App