如何从UWP中的应用程序包中的位置访问二进制资源文件(Windows 10)

时间:2016-01-12 16:37:53

标签: c# windows-10 uwp

在Windows 8.1(Silverlight)下,我的面向电话的C#应用​​程序使用以下代码从我的应用程序包访问二进制文件:

BinaryWriter fileWriter = new BinaryWriter(new IsolatedStorageFileStream("myWorkingStreamIOfile.pcm", FileMode.Create, fileStorage));

var uri = new Uri("assets/ myFileInMyProjectAssets.pcm", UriKind.Relative);
var res = App.GetResourceStream(uri);
long fileLength = res.Stream.Length;
BinaryReader fileReader = new BinaryReader(res.Stream);
var buffer = new byte[1024];
int readCount = 0;
while (readCount < fileLength)
{
    int read = fileReader.Read(buffer, 0, buffer.Length);
    readCount += read;
    fileWriter.Write(buffer, 0, read);
}

但UWP下不再提供“GetResourceStream”。关于如何在Window 10下实现上述目标的任何帮助将非常受欢迎。

谢谢!

1 个答案:

答案 0 :(得分:3)

主要区别在于如何打开文件。在下面的示例中,我从应用程序包内的/ Assets文件夹中打开文件(记得将文件设置为Build Action ContentCopy to output directory),然后将二进制内容复制到文件中在本地应用程序数据文件夹中,与代码中的方式相同。

此外,我省略了检查,但如果找不到文件,StorageFile.GetFileFromApplicationUriAsync()将抛出异常。

// Create or overwrite file target file in local app data folder
var fileToWrite = await ApplicationData.Current.LocalFolder.CreateFileAsync("myWorkingStreamIOfile.pcm", CreationCollisionOption.ReplaceExisting);
// Open file in application package
var fileToRead = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/myFileInMyProjectAssets.pcm", UriKind.Absolute));

byte[] buffer = new byte[1024];
using (BinaryWriter fileWriter = new BinaryWriter(await fileToWrite.OpenStreamForWriteAsync()))
{
    using (BinaryReader fileReader = new BinaryReader(await fileToRead.OpenStreamForReadAsync()))
    {
        long readCount = 0;
        while (readCount < fileReader.BaseStream.Length)
        {
            int read = fileReader.Read(buffer, 0, buffer.Length);
            readCount += read;
            fileWriter.Write(buffer, 0, read);
        }
    }
}

以下是适用于通用应用的URI格式的优质资源:https://msdn.microsoft.com/en-us/library/windows/apps/jj655406.aspx