现在的位置: 首页 > 综合 > 正文

WP7 IsolatedStorage–读取、保存二进制文件

2014年01月25日 ⁄ 综合 ⁄ 共 1908字 ⁄ 字号 评论关闭

引用命名空间:

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:

private void button1_Click(object sender, RoutedEventArgs e)
        {
            StreamResourceInfo streamresouceinfo = Application.GetResourceStream(new Uri(strFileName, UriKind.Relative));
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (myIsolatedStorage.FileExists(strFileName))
                {
                    myIsolatedStorage.DeleteFile(strFileName);
                }
                using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(strFileName, FileMode.Create, myIsolatedStorage))
                {
                    using (BinaryWriter binarywriter = new BinaryWriter(fileStream))
                    {
                        Stream resoucestream = streamresouceinfo.Stream;
                        long llength = resoucestream.Length;
                        byte[] buffer = new byte[32];
                        int readCount = 0;
                        using (BinaryReader binaryreader = new BinaryReader(streamresouceinfo.Stream))
                        {
                            while (readCount < llength)
                            {
                                int dActual = binaryreader.Read(buffer, 0, buffer.Length);//先读取到数组中
                                readCount += dActual;
                                binarywriter.Write(buffer, 0, dActual);//保存
                            }
                        }
                    }
                }
            }
        }

读取MP3:

private void button2_Click(object sender, RoutedEventArgs e)
        {
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(strFileName, FileMode.Open, FileAccess.Read))
                {
                    this.mediaElement1.SetSource(fileStream);
                }
            }
        }

抱歉!评论已关闭.