本文介绍了基于文件的缓存c#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以提出一些建议,以便在c#中实现基于文件的缓存.我需要为我的对象实现asp样式的缓存,但不是在内存中,而是在文件系统中,因为对象很大.
预先感谢.

Can anybody give some suggestions ow to implement file based cache in c#. I need to implement asp style cache for my objects but not in memory but in file system because object are large.
Thanks in advance.

推荐答案


public static class FileBasedCahce {
    static Dictionary<string, string> _FileMap;
    const string MAPFILENAME = "FileBasedCahceMAP.dat";
    public static string DirectoryLocation = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
    static FileBasedCahce() {
        if (!Directory.Exists(DirectoryLocation))
            throw new ArgumentException("directoryLocation msu exist");
        if (File.Exists(MyMapFileName)) {
            _FileMap = DeSerializeFromBin<Dictionary<string, string>>(MyMapFileName);
        } else
            _FileMap = new Dictionary<string, string>();
    }
    public static T Get<T>(string key) where T:new(){
        if (_FileMap.ContainsKey(key))
            return (T)DeSerializeFromBin<T>(_FileMap[key]);
        else
            throw new ArgumentException("Key not found");
    }
    public static void Insert<T>(string key, T value) {
        if (_FileMap.ContainsKey(key)) {
            SerializeToBin(value, _FileMap[key]);
        } else {
            _FileMap.Add(key, GetNewFileName);
            SerializeToBin(value, _FileMap[key]);
        }
        SerializeToBin(_FileMap, MyMapFileName);
    }
    private static string GetNewFileName {
        get {
            return Path.Combine(DirectoryLocation, Guid.NewGuid().ToString());
        }
    }
    private static string MyMapFileName {
        get {
            return Path.Combine(DirectoryLocation, MAPFILENAME);
        }
    }
    private  static void SerializeToBin(object obj, string filename) {
        Directory.CreateDirectory(Path.GetDirectoryName(filename));
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
            bf.Serialize(fs, obj);
        }
    }
    private static T DeSerializeFromBin<T>(string filename) where T : new() {
        if (File.Exists(filename)) {
            T ret = new T();
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) {
                ret = (T)bf.Deserialize(fs);
            }
            return ret;
        } else
            throw new FileNotFoundException(string.Format("file {0} does not exist", filename));
    }

}



这篇关于基于文件的缓存c#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 15:55