WP_从独立存储区读取缓存的图片

时间:2023-03-09 01:46:51
WP_从独立存储区读取缓存的图片
 

    ///<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;

        }

    }