///<summary>

    /// 独立存储缓存的图片源

    /// 用法:item.img = new StorageCachedImage(newUri(http://www.baidu.com/12.jpg));

    ///</summary>

    public sealed class StorageCachedImage : BitmapSource

    {

        private readonly Uri uriSource;

        private readonly string filePath;

        private const string CacheDirectory = "CachedImages";

        static StorageCachedImage()

        { 

            //创建缓存目录

            using (var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())

            {

                if (!isolatedStorageFile.DirectoryExists(CacheDirectory))

                {

                    isolatedStorageFile.CreateDirectory(CacheDirectory);

                }

            }

        }

        ///<summary>

        /// 创建一个独立存储缓存的图片源

        ///</summary>

        ///<param name="uriSource"></param>

        public StorageCachedImage(Uri uriSource)

        {

            this.uriSource = uriSource;

            string sUrl = uriSource.AbsolutePath;

            //文件路径

            filePath = Path.Combine(CacheDirectory, sUrl.Substring(sUrl.LastIndexOf("/") + 1, sUrl.Length - sUrl.LastIndexOf("/") - 1));

            OpenCatchSource();

        }

        ///<summary>

        /// 打开缓存源

        ///</summary>

        private void OpenCatchSource()

        {

            //网络可用时,下载图片(网络不可用时读取本地缓存)

            if (CommonConst.CheckNetWorking())

            {

                SetWebStreamSource();

            }

            else

            {

                bool exist;

                using (var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())

                {

                    exist = isolatedStorageFile.FileExists(filePath);

                }

                if (exist)

                {

                    SetCacheStreamSource();

                }

                else

                {

                    //SetWebStreamSource();

                }

            }

        }

        ///<summary>

        /// 设置缓存流到图片

        ///</summary>

        private void SetCacheStreamSource()

        {

            using (var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())

            using (var stream = isolatedStorageFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))

            {

                SetSource(stream);

            }

        }

        ///<summary>

        /// 下载Uri中的图片

        ///</summary>

        private void SetWebStreamSource()

        {

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(uriSource);

            httpWebRequest.AllowReadStreamBuffering = true;

            httpWebRequest.BeginGetResponse(ResponseCallBack, httpWebRequest);

        }

        ///<summary>

        /// 下载回调

        ///</summary>

        ///<param name="asyncResult"></param>

        private void ResponseCallBack(IAsyncResult asyncResult)

        {

            var httpWebRequest = asyncResult.AsyncState as HttpWebRequest;

            if (httpWebRequest == null) return;

            try

            {

                var response = httpWebRequest.EndGetResponse(asyncResult);

                using (var stream = response.GetResponseStream())

                using (var isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())

                using (var fileStream = isolatedStorageFile.OpenFile

                (filePath, FileMode.OpenOrCreate, FileAccess.Write))

                {

                    CopyStream(stream, fileStream);

                }

                Dispatcher.BeginInvoke(SetCacheStreamSource);

            }

            catch (Exception err)

            {

                //Debug.WriteLine(err.Message);

            }

        }

        private static void CopyStream(System.IO.Stream input, IsolatedStorageFileStream output)

        {

            byte[] buffer = new byte[32768];

            long TempPos = input.Position;

            int readCount;

            do

            {

                readCount = input.Read(buffer, 0, buffer.Length);

                if (readCount > 0)

                {

                    output.Write(buffer, 0, readCount);

                }

            } while (readCount > 0);

            input.Position = TempPos;

        }

    }

WP_从独立存储区读取缓存的图片的更多相关文章

  1. C#从证书存储区读取证书

    using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptograph ...

  2. WP开发图片保存到独立存储并从独立存储中读取

    需要添加引用命名空间 using System.IO; using System.IO.IsolatedStorage; 1.将图片保存到独立存储空间 using (IsolatedStorageFi ...

  3. 调用EF的存储过程报“存储区数据提供程序返回的数据读取器所具有的列数对于所请求的查询不够”问题

    在运用Entity Framework调用存储过程的时候,遇到"调用EF的存储过程报"调用EF的存储过程报“存储区数据提供程序返回的数据读取器所具有的列数对于所请求的查询不够”问题 ...

  4. 第21章 DMA—直接存储区访问

    本章参考资料:<STM32F76xxx参考手册>DMA控制器章节. 学习本章时,配合<STM32F76xxx参考手册>DMA控制器章节一起阅读,效果会更佳,特别是涉及到寄存器说 ...

  5. 第21章 DMA—直接存储区访问—零死角玩转STM32-F429系列

    第21章     DMA—直接存储区访问 全套200集视频教程和1000页PDF教程请到秉火论坛下载:www.firebbs.cn 野火视频教程优酷观看网址:http://i.youku.com/fi ...

  6. DMA—直接存储区访问

    本章参考资料:< STM32F4xx 中文参考手册> DMA 控制器章节.学习本章时,配合< STM32F4xx 中文参考手册> DMA 控制器章节一起阅读,效果会更佳,特别是 ...

  7. PHP 开发 APP 接口 学习笔记与总结 - APP 接口实例 [3] 首页 APP 接口开发方案 ② 读取缓存方式

    以静态缓存为例. 修改 file.php line:11 去掉 path 参数(方便),加上缓存时间参数: public function cacheData($k,$v = '',$cacheTim ...

  8. 转:内存区划分、内存分配、常量存储区、堆、栈、自由存储区、全局区[C++][内存管理][转载]

    内存区划分.内存分配.常量存储区.堆.栈.自由存储区.全局区[C++][内存管理][转载] 一. 在c中分为这几个存储区1.栈 - 由编译器自动分配释放2.堆 - 一般由程序员分配释放,若程序员不释放 ...

  9. WP8 独立存储 总结3(应用设置)

    •可在独立存储中使用ApplicationSettings对象•在独立存储中存储键/值对的Dictionary方式存储 •存储的对象将永久保存 在应用设置中保存数据 void saveString(s ...

随机推荐

  1. 1.运行Android Studio,一直提示:Error running app: Instant Run requires 'Tools | Android | Enable ADB integration' to be enabled.

    1.解决问题办法:菜单栏,Tools -> Adnroid -> enable ADB integration勾上 2.暂时性的解决方案:在Android Studio中的:Prefere ...

  2. nginx重写规则报nginx: [emerg] directive "rewrite" is not terminated by ";"

    对于下面的重写规则 rewrite ^/gongying/([\d]{8})_([\d]+).html$ /index.php?app=support&act=view&pts=$1& ...

  3. HTTP 1.1与HTTP 1.0的比较

    HTTP 1.1与HTTP 1.0的比较 一个WEB站点每天可能要接收到上百万的用户请求,为了提高系统的效率,HTTP 1.0规定浏览器与服务器只保持短暂的连接,浏览器的每次请求都需要与服务器建立一个 ...

  4. Python标准库02 时间与日期 (time, datetime包)

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python具有良好的时间和日期管理功能.实际上,计算机只会维护一个挂钟时间(wa ...

  5. 聚合查询中的Group by

    2005版本以上的sql server 查询中如果既包含聚合函数列(诸如sum ,count,avg,max等)又存在一般列的情况,则查询字符串结尾必须包含Group By [某一般列].  其实微软 ...

  6. WPF NotifyIcon and Taskbar 任务栏示例

    Demo Source 转自:http://www.codeproject.com/Articles/36788/WPF-XAML-NotifyIcon-and-Taskbar-System-Tray ...

  7. Mac添加环境变量的三种方法

    法一: sudo vi /etc/paths 来编辑 paths,将环境变量添加到 paths 中. vim 是一个编辑器,另外还有几个,如:Pico,Emacs. Hint:输入环境变量时,不用一个 ...

  8. ramBufferSizeMB

    索引算法确定 的情况下,影响Lucene索引速度的因素 MaxBufferedDocs这个参数默认是disabled的,因为Lucene中还用另外一个参数(RAMBufferSizeMB)控制这个bu ...

  9. AndroidManifest.xml 屏幕上下反转

    通常我们的应用只会设计成横屏或者竖屏,锁定横屏或竖屏的方法是在AndroidManifest.xml 文件中设定属性android:screenOrientation为"landscape& ...

  10. Oracle 删除数据后释放数据文件所占磁盘空间

    测试的时候向数据库中插入了大量的数据,测试完成后删除了测试用户以及其全部数据,但是数据文件却没有缩小.经查阅资料之后发现这是 Oracle “高水位”所致,那么怎么把这些数据文件的大小降下来呢?解决办 ...