Cache Helper

// April 16th, 2013 // Useful Code

This was put together rather quickly while writing an application to download various web pages and images. I decided to use a cache system to keep from downloading the same file multiple times while the user decided between which image(s) to keep.

Entire Helper Class


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;

namespace Helpers
{
    static class CacheHelper
    {
        private static string CacheFolderPath
        {
            get
            {
                return Properties.Settings.Default.CacheFolder;
            }
        }
        private static long CacheFolderLimit
        {
            get
            {
                return 1073741824; //1GB (1024 * 1024 * 1024)
            }
        }

        private static void CheckCacheSize()
        {
            DirectoryInfo cacheFolder = new DirectoryInfo(CacheFolderPath);
            FileInfo[] fileList; // = cacheFolder.GetFiles("*.*", SearchOption.AllDirectories);

            if (!cacheFolder.Exists)
                cacheFolder.Create();

            //IF THE CACHE FOLDER IS TO LARGE THEN DELETE THE OLDEST 10 FILES
            while ((fileList = DirectoryHelper.GetAllFiles(CacheFolderPath, null, null)).Sum(a => a.Length) > CacheFolderLimit)
            {
                fileList.OrderBy(a => a.CreationTime).First().Delete();
            }
        }

        public static Stream DownloadFileStream(string URL)
        {
            return File.OpenRead(DownloadFileToDisk(URL));
        }
        public static byte[] DownloadFileBytes(string URL)
        {

            return File.ReadAllBytes(DownloadFileToDisk(URL));

        }
        public static string DownloadFileToDisk(string URL)
        {
            //CLEAR SOME CACHE IF NEEDED
            CheckCacheSize();

            Uri tmpURI = new Uri(URL);
            string tmpFileLocation = CacheFolderPath + tmpURI.LocalPath.Replace('/', '\\');
            FileInfo tmpFileInfo = new FileInfo(tmpFileLocation);

            //IF THE FILE EXISTS ON DISK THEN OPEN IT, OTHERWISE DOWNLOAD
            if (!tmpFileInfo.Exists)
            {
                using (WebClient tmpClient = new WebClient())
                {
                    //MAKE SURE THE SUB FOLDER EXISTS
                    tmpFileInfo.Directory.Create();

                    //WRITE THE FILE TO THE CACHE
                    File.WriteAllBytes(tmpFileLocation, tmpClient.DownloadData(tmpURI));
                }
            }

            //RETURN THE FILE LOCATION BACK
            return tmpFileLocation;
        }
    }

    class DirectoryHelper
    {
        private static void GetAllFilesInDirectory(string Folder, IEnumerable<string> FileTypes, IEnumerable<string> Exclusions, ref List<FileInfo> FileList)
        {
            DirectoryInfo rootFolder = new DirectoryInfo(Folder);
            FileList.AddRange(rootFolder.GetFiles("*.*", SearchOption.TopDirectoryOnly).Where(a => FileTypes!= null ? FileTypes.Contains(a.Extension.ToUpper()) : true).Where(a=> Exclusions!= null ? !Exclusions.Any(e=> a.Name.ToUpper().Contains(e)) : true).ToArray());

            foreach (DirectoryInfo tmpDirectory in rootFolder.GetDirectories())
            {
                GetAllFilesInDirectory(tmpDirectory.FullName, FileTypes, Exclusions, ref FileList);
            }
        }

        public static FileInfo[] GetAllFiles(string Folder, IEnumerable<string> FileTypes, IEnumerable<string> Exclusions)
        {
            List<FileInfo> tmpReturn = new List<FileInfo>();
            GetAllFilesInDirectory(Folder, FileTypes!= null ? FileTypes.Select(a=> a.ToUpper()) : null, Exclusions != null ? Exclusions.Select(a=> a.ToUpper()) : null, ref tmpReturn);

            return tmpReturn.ToArray();
        }
    }

}
Be Sociable, Share!
  • RSS
  • Twitter
  • Facebook
  • LinkedIn
  • DeviantArt