///<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. 树莓派,使用opencv调用自带的摄像头

    OpenCV&Pi Cam – Step 1 : Install It’s quite easy to install your new Pi Camera. Installation pro ...

  2. Timer与ScheduledThreadPoolExecutor的比较

    推荐还是用第二种方法,即用ScheduledThreadPoolExecutor,因为它不需要像timer那样需要在里面再用一个线程池来保证计时的准确.(前提是线程池必须要大于1个线程) 1.time ...

  3. Mac 终端常用命令备忘

    Tab 补全 pwd 显示路径 一 .ls ls -lh   查看当前路径详细文件 ls ..     返回上级目录 ls -a   显示隐藏文件 ls -a -l 以详细列表显示 ls ../../ ...

  4. Getting started with SciPy for .NET

    Getting started with SciPy for .NET 1.) IronPython Download and install IronPython 2.7, this will re ...

  5. centos安装——usb安装技术问题整理

    1) 官网How tohttp://wiki.centos.org/HowTos/InstallFromUSBkey 2)我安装碰到的问题:http://www.douban.com/group/to ...

  6. 搭建一个springmvc helloworld程序

    1.加jar包,需要8个,从springframework里面选 logging core aop context expression bean web webmvc 2.配置web.xml,在文件 ...

  7. 【转】SQL Server 查询表的记录数(3种方法,推荐第一种)

    --SQL Server 查询表的记录数 --one: 使用系统表. SELECT object_name (i.id) TableName, rows as RowCnt FROM sysindex ...

  8. C#中如何设置窗体的默认按钮和取消按钮

    可以直接在窗体的AcceptButton和CancelButton中设置相应的按钮. 也可以在后头通过代码设置: this.AcceptButton = (IButtonControl)btnSave ...

  9. Django网站直接使用supervisor部署

    python manage.py createsuperuser python manage.py migrate 生成网站的supervisor配置文件: echo_supervisord_conf ...

  10. OC基础(22)

    NSMutableString基本概念 NSMutableString常用方法 NSMutableString练习 *:first-child { margin-top: 0 !important; ...