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



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

但是"GetResourceStream"在UWP下已经不可用了。对于如何在窗口10下实现上述目标的任何帮助,我们都将非常欢迎。

谢谢!

主要区别在于如何打开文件。在下面的示例中,我从应用程序包内的/Assels文件夹打开文件(记住将文件设置为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

最新更新