如何将MemoryCache内容转储到一个文件How to dump contents of MemoryCache to a file

- 此内容更新于:2015-01-06
主题:

我想MemoryCache对象的内容转储到一个文件用于调试目的。 我怎么能这样做呢? 代码: 但这给了我一个运行时错误代码表示“无法序列化MemoryCache”。

原文:

I want to dump the contents of MemoryCache object to a file for debugging purpose.

How can I do this?

Code:

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
    }
}

But this code gives me a runtime error saying "Unable to serialize MemoryCache".

Sriram Sakthivel的回复:你需要做手工。为MemoryCache # 39;t可序列化的。顺便说一句,你可以# 39;t找到任何有用的即使你使用BinaryFormatter设法甩掉它。它不会在可读的格式。

(原文:You need to do it manually. MemoryCache isn't serializable. Btw you can't find anything helpful even though you managed to dump it using BinaryFormatter. It will not be in readable format.)

Mikant的回复:& lt;off>你不应该手动调用fileStream.Close()方法使用语句导致它被设计为自动处理(因此关闭)fileStream object</ off>

(原文:<off>you should not manually call fileStream.Close() method with using statement cause it is designed to automatically dispose (and thus close) fileStream object</off>)

解决方案:
就设法把钥匙使用这个代码。使用json序列化。 倾销的所有缓存中对象创建一个大文件,与内容杂乱。以上是我的需要脉冲微分。
原文:

Managed to just dump the keys using this bit of code. Used json to serialize.

  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
        }
    }

Dumping all the objects in the cache would create a seriously large file, cluttered with content. The above was suffient for my needs.