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

Get data from another UWP application

我不想访问存储在另一个 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?如果是,如何?

UWP 中的应用程序是沙盒化的,因此您无法轻易访问它们的存储空间。有几个共享数据的选项:

是的。这只有在两个应用程序由同一发布者发布时才有可能。

此文件夹缓存名为PublisherCacheFolder

这里有一个 Blog Post 会详细解释这个。

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

<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;  
}

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

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