List all custom data stored in AppDomain

痞子三分冷 提交于 2019-12-05 03:01:27
        AppDomain domain = AppDomain.CurrentDomain;
        domain.SetData("testKey", "testValue");

        FieldInfo[] fieldInfoArr = domain.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
        foreach (FieldInfo fieldInfo in fieldInfoArr)
        {

            if (string.Compare(fieldInfo.Name, "_LocalStore", true) != 0)
                continue;
            Object value = fieldInfo.GetValue(domain);
            if (!(value is Dictionary<string,object[]>))
                return;
            Dictionary<string, object[]> localStore = (Dictionary<string, object[]>)value;
            foreach (var item in localStore)
            {
                Object[] values = (Object[])item.Value;
                foreach (var val in values)
                {
                    if (val == null)
                        continue;
                    Console.WriteLine(item.Key + " " + val.ToString());
                }
            }


        }
Oliver

Based on Frank59's answer but a bit more concise:

var appDomain = AppDomain.CurrentDomain;
var flags = BindingFlags.NonPublic | BindingFlags.Instance;
var fieldInfo = appDomain.GetType().GetField("_LocalStore", flags);
if (fieldInfo == null)
    return;
var localStore = fieldInfo.GetValue(appDomain) as Dictionary<string, object[]>;
if (localStore == null)
    return;
foreach (var key in localStore.Keys)
{
    var nonNullValues = localStore[key].Where(v => v != null);
    Console.WriteLine(key + ": " + string.Join(", ", nonNullValues));
}

Same solution, but as an F# extension method. May not need the null check. https://gist.github.com/ctaggart/30555d3faf94b4d0ff98

type AppDomain with
    member x.LocalStore
        with get() =
            let f = x.GetType().GetField("_LocalStore", BindingFlags.NonPublic ||| BindingFlags.Instance)
            if f = null then Dictionary<string, obj[]>()
            else f.GetValue x :?> Dictionary<string, obj[]>

let printAppDomainObjectCache() =
    for KeyValue(k,v) in AppDomain.CurrentDomain.LocalStore do
        printfn "%s" k
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!