(5)[wp7数据存储] WP7 IsolatedStorage系列篇-——读取、保存二进制文件 [复制链接]

 

本帖最后由 agameboy 于 2012-5-17 17:09 编辑

二进制文件一般被认为是一组序列字节,这一章主要是读取、保存二进制文件 ,更多的文章请参考WP7 IsolatedStorage系列篇
引用命名空间:
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Resources;

二进制文件一般被认为是一组序列字节。一般来说一个二进制文件可能包含任何形式的二进制编码的数据类型。例如:.mp3文件,.jpg文件,.db文件都可以看做二进制文件。本篇内容将以MP3文件为例。
示例中首先检查文件是否已经存在,然后把“Hello.mp3”文件保存到隔离存储空间。
我们首先创建一个文件流,然后使用BinaryWriter和BinaryReader在隔离层存储空间中创建一个新的MP3文件并且把“Hello.mp3”的数据复制过去。
提示:分块读取文件有利于减少内存消耗和提高性能。
定义变量名称:
const string strFileName = "Hello.mp3";

保存MP3:
  1. private void button1_Click(object sender, RoutedEventArgs e)
  2.         {
  3.             StreamResourceInfo streamresouceinfo = Application.GetResourceStream(new Uri(strFileName, UriKind.Relative));
  4.             using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
  5.             {
  6.                 if (myIsolatedStorage.FileExists(strFileName))
  7.                 {
  8.                     myIsolatedStorage.DeleteFile(strFileName);
  9.                 }
  10.                 using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(strFileName, FileMode.Create, myIsolatedStorage))
  11.                 {
  12.                     using (BinaryWriter binarywriter = new BinaryWriter(fileStream))
  13.                     {
  14.                         Stream resoucestream = streamresouceinfo.Stream;
  15.                         long llength = resoucestream.Length;
  16.                         byte[] buffer = new byte[32];
  17.                         int readCount = 0;
  18.                         using (BinaryReader binaryreader = new BinaryReader(streamresouceinfo.Stream))
  19.                         {
  20.                             while (readCount < llength)
  21.                             {
  22.                                 int dActual = binaryreader.Read(buffer, 0, buffer.Length);//先读取到数组中
  23.                                 readCount += dActual;
  24.                                 binarywriter.Write(buffer, 0, dActual);//保存
  25.                             }
  26.                         }
  27.                     }
  28.                 }
  29.             }
  30.         }
复制代码



读取MP3:
  1. private void button2_Click(object sender, RoutedEventArgs e)
  2.         {
  3.             using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
  4.             {
  5.                 using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(strFileName, FileMode.Open, FileAccess.Read))
  6.                 {
  7.                     this.mediaElement1.SetSource(fileStream);
  8.                 }
  9.             }
  10.         }
复制代码
posted @ 2012-11-29 14:34  BellingWP  阅读(142)  评论(0编辑  收藏  举报