从另一个UWP应用程序获取数据

时间:2017-02-08 12:59:07

标签: uwp windows-10-universal

我不想访问存储在另一个UWP应用程序中的数据。我看到您可以使用以下代码将数据保存在UWP应用程序的LocalState文件夹中:

Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Globalization.DateTimeFormatting.DateTimeFormatter formatter =
            new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("longtime");

StorageFile sampleFile = await localFolder.CreateFileAsync("example.txt",
                         CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));

Here is the official documentation

所以使用这段代码,我在第一个UWP项目中创建了一个名为example.txt的文件。

是否可以从第二个UWP项目访问example.txt?如果是,怎么样?

3 个答案:

答案 0 :(得分:2)

UWP中的应用程序是沙盒,因此您无法轻松访问其存储。有几种共享数据的选项:

答案 1 :(得分:1)

是。只有当两个应用程序都由同一发布者发布时,才可能这样做。

此文件夹缓存名为PublisherCacheFolder

这是一个Blog Post,会详细解释这一点。

您需要在appmanifest中添加扩展程序才能在您希望共享数据的所有应用中完成此操作。

<Extensions>  
  <Extension Category="windows.publisherCacheFolders">  
    <PublisherCacheFolders>  
      <Folder Name="Downloads" />  
    </PublisherCacheFolders>  
  </Extension>  
</Extensions>

有一个很好的视频在Channel9上解释了这一点。跳到第19分钟。

以下是来自另一个Blog的简单的写入和读取方法。

async void WritetoPublisherFolder(string Text)  
{  
    StorageFolder SharedFolder = Windows.Storage.ApplicationData.Current.GetPublisherCacheFolder("CommonFolder");  
    StorageFile newFile = await SharedFolder.CreateFileAsync("SharedFile.txt", CreationCollisionOption.OpenIfExists);  
    await FileIO.WriteTextAsync(newFile, Text);  
}  

async Task<string> ReadFromSharedFolder()  
{  
    StorageFolder SharedFolder = Windows.Storage.ApplicationData.Current.GetPublisherCacheFolder("CommonFolder");  
    StorageFile newFile = await SharedFolder.GetFileAsync("SharedFile.txt");  
    var text = await FileIO.ReadTextAsync(newFile);  
    return text;  
}

答案 2 :(得分:1)

您还可以创建可以共享任何数据的AppService。基本上,提供商将托管服务,需要数据的应用程序应该使用该服务。

更多信息:https://docs.microsoft.com/en-us/windows/uwp/launch-resume/how-to-create-and-consume-an-app-service