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

问题描述 投票:1回答:2

我想将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”。

c# caching
2个回答
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
        }
    }

倾倒缓存中的所有对象会创建一个非常大的文件,内容杂乱无章。以上满足了我的需求。


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

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

© www.soinside.com 2019 - 2024. All rights reserved.