如何将MemoryCache的内容转储到文件中

时间:2015-01-05 11:56:27

标签: c# caching

我想将MemoryCache对象的内容转储到文件中以进行调试。

我该怎么做?

代码:

private static readonly MemoryCache OutputCache = new MemoryCache("output-cache");    

public static void DumpMemoryCacheToFile(string filePath)
{
    try
    {
        using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
        {
            IFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

            bf.Serialize(fileStream, OutputCache);
            fileStream.Close();
        }
    }
    catch
    {
        // Do nothing
    }
}

但是这段代码给我一个运行时错误,说“无法序列化MemoryCache”。

2 个答案:

答案 0 :(得分:0)

管理只需使用这段代码转储密钥。使用json序列化。

  public static void DumpMemoryCacheToFile(string filePath)
    {
        try
        {
            using (var file = new StreamWriter(filePath, true))
            {
                foreach (var item in OutputCache)
                {
                    string line = JsonConvert.SerializeObject(item.Key);
                    file.WriteLine(line);
                }
            }
        }
        catch
        {
            // Do nothing
        }
    }

转储缓存中的所有对象会产生一个非常大的文件,内容混乱。以上内容足以满足我的需求。

答案 1 :(得分:0)

var memoryCache = MemoryCache.Default;
var allObjects = memoryCache.ToDictionary(
    cachedObject => cachedObject.Key,
    cachedObject => cachedObject.Value
);
var contentsAsJson = Newtonsoft.Json.JsonConvert.SerializeObject(allObjects, Formatting.Indented);
System.IO.File.WriteAllText("c:\\myCacheContents.txt", contentsAsJson);

这是一个非常简单的缓存,其中的对象可以轻松地序列化(即不包含自引用对象),并且在迭代其内容时,我们并不关心锁定缓存。