1 using System.IO.IsolatedStorage;
2 using System.IO;
3 using System.Windows.Resources;
保存MP3文件到隔离存储空间
示例中首先检查文件是否已经存在,然后把“Battery_Low.mp3”文件保存到隔离存储空间。
我们首先创建一个文件流,然后使用BinaryWriter和BinaryReader在隔离层存储空间中创建一个新的MP3文件并且把“Battery_Low.mp3”的数据复制过去。
提示:分块读取文件有利于减少内存消耗和提高性能。
01 private const string FileName = "Battery_Low.mp3";
02 private void btnSave_Click(object sender, RoutedEventArgs e)
03 {
04 StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(FileName, UriKind.Relative));
05
06 using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
07 {
08 if (myIsolatedStorage.FileExists(FileName))
09 {
10 myIsolatedStorage.DeleteFile(FileName);
11 }
12
13 using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(FileName, FileMode.Create, myIsolatedStorage))
14 {
15 using (BinaryWriter writer = new BinaryWriter(fileStream))
16 {
17 Stream resourceStream = streamResourceInfo.Stream;
18 long length = resourceStream.Length;
19 byte[] buffer = new byte[32];
20 int readCount = 0;
21 using (BinaryReader reader = new BinaryReader(streamResourceInfo.Stream))
22 {
23 // read file in chunks in order to reduce memory consumption and increase performance
24 while (readCount < length)
25 {
26 int actual = reader.Read(buffer, 0, buffer.Length);
27 readCount += actual;
28 writer.Write(buffer, 0, actual);
29 }
30 }
31 }
32 }
33 }
34 }
从隔离存储空间中读取MP3文件
示例中首先从隔离存储空间打开了一个名为Battery_Low.mp3的文件,并且把内容设置为一个媒体元素的数据源。