如何从数组结构中获取mime名称

时间:2014-12-19 07:33:05

标签: c#

我有MimeVideo结构并在列表中使用它来存储mime视频文件。我试图通过mimefile获取Ext名称的值来将其存储在MediaTypeHeaderValue中。怎么做?

struct MimeVideo
{
    private readonly string _ext;
    private readonly string _file;
    public MimeVideo(string ext, string file)
    {
        this._ext = ext;
        this._file = file;
    }
    public string Ext { get { return _ext; } }
    public string File { get { return _file; } }

}
static readonly IList<MimeVideo> MimeNames = new ReadOnlyCollection<MimeVideo>
(new[] {
     new MimeVideo (".mp4", "video/mp4"),
     new MimeVideo (".ogg", "application/ogg"),
     new MimeVideo (".ogv", "video/ogg"),
     new MimeVideo (".webm", "video/webm")
});

private static MediaTypeHeaderValue GetMimeNameFromExt(string ext)
{
    string name ;
     get the name of file using ext 
    if (MimeNames // get filename by using ext)
        return new MediaTypeHeaderValue(name );
    else
        return new MediaTypeHeaderValue(MediaTypeNames.Application.Octet);
}

1 个答案:

答案 0 :(得分:1)

您可以使用Enumerable.FirstOrDefault

private static MediaTypeHeaderValue GetMimeNameFromExt(string ext)
{
   MimeVideo first = MimeNames
      .FirstOrDefault(m => m.Ext.Equals(ext, StringComparison.InvariantCultureIgnoreCase));
   if(first == null) 
       return new MediaTypeHeaderValue(MediaTypeNames.Application.Octet);
   else
       return new MediaTypeHeaderValue(first.File);
}

Where + DefaultIfEmpty

private static MediaTypeHeaderValue GetMimeNameFromExt(string ext)
{
    return MimeNames
        .Where(m => m.Ext.Equals(ext, StringComparison.InvariantCultureIgnoreCase))
        .Select(m => new MediaTypeHeaderValue(m.File))
        .DefaultIfEmpty(new MediaTypeHeaderValue(MediaTypeNames.Application.Octet))
        .First();
}

您还没有看到如何获得扩展程序,我建议使用System.IO.Path.GetExtension。我也会改用Dictionary<string, MimeVideo>