有效地将扩展字符串映射到图标URL

时间:2012-11-04 02:26:12

标签: c# asp.net sharepoint search file-type

我在CMS(sharepoint 2013)上托管了一个内置搜索的ASP.NET Web应用程序。

使用搜索运行文件查询时,文件类型的唯一指示是扩展字符串,格式不带句点"PNG" or "JPG"

我没有收回文件,我只是获取描述该文件的元数据。为了清楚起见,我没有得到任何MIME类型或文件对象,我只能得到一个扩展字符串。

我在网站上查看了这样一个问题,我没有看到。

似乎可能有某种方法返回一个字符串,并在其签名中接受一个字符串输入,并搜索某种类型的对象集合,如下所示:

最终结果:

static class FileIcons
{
    static public string PDF = string.Format("{0}", SPContext.Current.Site.ServerRelativeUrl + "_layouts/15/monkeysphere/images/icons/pdf.png");
    static public string Word = string.Format("{0}", SPContext.Current.Site.ServerRelativeUrl + "_layouts/15/monkeysphere/images/icons/word.png");
    static public string Generic = string.Format("{0}", SPContext.Current.Site.ServerRelativeUrl + "_layouts/15/monkeysphere/images/icons/file.png");

    static private Dictionary<String, String> IconUrls = new Dictionary<String,String>() 
                        {
                            {"JPG", Picture},{"JPEG", Picture},{"GIF", Picture},{"PNG", Picture},
                            {"PDF", PDF},{"DOC", Word},{"DOCX", Word},{"XLS", Excel},{"XLSX", Excel},{"PPT", PowerPoint},{"PPTX", PowerPoint}
                        };

    static public string GetIconUrlFromExtension(string extension)
    {
        var formattedExtension = extension.Trim().Replace(".","").ToUpper();
        if (string.IsNullOrEmpty(extension) || !IconUrls.ContainsKey(formattedExtension))
            return Generic;
        return IconUrls[formattedExtension];
    }
}

1 个答案:

答案 0 :(得分:1)

我认为Dictionary是更好的选择。像这样:

public static class IconUrls {
    static Dictionary<string, string> _extensions;
    static string DefaultUrl = "~/siteroot/images/icons/genericicon.png";

    static IconUrls {
        extensions = new Dictionary<string, string>() {
            { "JPG", "~/siteroot/images/icons/jpegicon.png" }, 
            { "JPEG", "~/siteroot/images/icons/jpegicon.png" }
        }
    }

    public static Dictionary<string, string> Extensions {
        get {
            return _extensions;
        }
    }

    public static string GetIconUrl(string extension) {
    {
        if(string.IsNullOrEmpty(extension) || !_dictionary.ContainsKey(extension.Trim().ToUpper()))
            return DefaultUrl;
        return _extensions[extension.Trim().ToUpper()];
    }
}

您还可以从配置文件加载映射,以免硬编码。