Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建缓存并基于输入参数返回单个值!_C#_Xml - Fatal编程技术网

C# 创建缓存并基于输入参数返回单个值!

C# 创建缓存并基于输入参数返回单个值!,c#,xml,C#,Xml,我需要使用XML文件创建缓存。这是我将要使用的方法的签名。我希望此方法根据密钥产品名称返回id。因此,我希望它以编程方式一次性创建一个缓存,然后仅当找不到该键时才添加该缓存 public static string getProductId(string product_name) public static string getTechId(string fieldName) { Cache cache = HttpContext.Current.Cache;

我需要使用XML文件创建缓存。这是我将要使用的方法的签名。我希望此方法根据密钥产品名称返回id。因此,我希望它以编程方式一次性创建一个缓存,然后仅当找不到该键时才添加该缓存

public static string getProductId(string product_name)
    public static string getTechId(string fieldName)
    {
        Cache cache = HttpContext.Current.Cache;  //neeed to change this.
        string cacheNameEpm = product_name + "TechName";

        if (cache[cacheNameEpm] == null)
        {
            XPathDocument doc = new XPathDocument(HttpContext.Current.Request.MapPath("inc/xml/prd.xml"));
            XPathNavigator navigator = doc.CreateNavigator();
            string selectName = "/Products/Product[ProductName ='" + fieldName + "']/ProductId";
            XPathNodeIterator nodes = navigator.Select(selectName);

            if (nodes.Count > 0)
            {
                nodes.MoveNext();
                cache.Add(cacheNameEpm, nodes.Current.Value, null, DateTime.Now + new TimeSpan(4, 0, 0), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
            }
        }
        return cache[cacheNameEpm] as string;
    }
以下是xml文件:

<Products>
    <Product>
        <ProductName>PDPArch</ProductName>
        <ProductId>57947</ProductId>
    </Product>
    <Product>
        <ProductName>TYFTType</ProductName>
        <ProductId>94384</ProductId>
    </Product>
</Products>

为什么不读入整个XML文件并将其添加到字典中呢?您可以将整个词典粘贴到缓存中,并将其保留在缓存中。

您希望我们为您编码,还是有具体问题?对于前者,我们应该讨论我的费率。我已经有代码了。但我想优化它,所以我想做不同的!我可以分享。有什么特别的原因你不只是缓存整个东西吗?事实上这就是我需要做的。只做一次缓存,一切正常!!需要创建1次缓存请注意,它将在4小时后过期,因此实现需要不同。它必须是1次缓存,而不是当前的实现方式。