我有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);
}
答案 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>
。