boll指标详解,WP7 Isolated Storage详解(8)-读取、保存二进制文件

二进制文件一般被认为是一组序列字节。一般来说一个二进制文件可能包含任何形式的二进制编码的数据类型。例如:.mp3文件,.jpg文件,.db文件都可以看做二进制文件。本篇内容将以MP3文件为例。
首先创建一个Windows Phone 7项目,在项目中添加一个MP3文件例如“Battery_Low.mp3”,然后在MainPage.xaml.cs(或其他页面文件)中引入命名空间:
using System.IO.IsolatedStorage; using System.IO; using System.Windows.Resources;

保存MP3文件到隔离存储空间

示例中首先检查文件是否已经存在,然后把“Battery_Low.mp3”文件保存到隔离存储空间。
我们首先创建一个文件流,然后使用BinaryWriter和BinaryReader在隔离层存储空间中创建一个新的MP3文件并且把“Battery_Low.mp3”的数据复制过去。
提示:分块读取文件有利于减少内存消耗和提高性能。
private const string FileName = "Battery_Low.mp3"; private void btnSave_Click(object sender, RoutedEventArgs e) { StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(FileName, UriKind.Relative)); using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { if (myIsolatedStorage.FileExists(FileName)) { myIsolatedStorage.DeleteFile(FileName); } using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(FileName, FileMode.Create, myIsolatedStorage)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { Stream resourceStream = streamResourceInfo.Stream; long length = resourceStream.Length; byte[] buffer = new byte[32]; int readCount = 0; using (BinaryReader reader = new BinaryReader(streamResourceInfo.Stream)) { // read file in chunks in order to reduce memory consumption and increase performance while (readCount < length) { int actual = reader.Read(buffer, 0, buffer.Length); readCount += actual; writer.Write(buffer, 0, actual); } } } } } }

从隔离存储空间中读取MP3文件

示例中首先从隔离存储空间打开了一个名为Battery_Low.mp3的文件,并且把内容设置为一个媒体元素的数据源。
private void btnRead_Click(object sender, RoutedEventArgs e) { using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(FileName, FileMode.Open, FileAccess.Read)) { this.mediaElement.SetSource(fileStream); } } }
提示:"mediaElement"是一个在MainPage.xaml中的媒体元素:
Tags:  兄弟宫详解 详解九章 事业宫详解 父母宫详解 boll指标详解

延伸阅读

最新评论

发表评论