C#获取图片文件扩展名的方法
下面我给各位朋友整理了一篇C#获取图片文件扩展名的例子,这里方法都非常的简单,我们只用到了image.RawFormat.Guid就实现了,具体看代码
例子
///<summary>
///根据图像获取图像的扩展名
///</summary>
///<paramname="image"></param>
///<returns></returns>
publicstaticStringGetExtension(Imageimage)
{
foreach(varpairinImageFormats)
{
if(pair.Value.Guid==image.RawFormat.Guid)
{
returnpair.Key;
}
}
thrownewBadImageFormatException();
}
使用方法如下:
using(varimg=Image.FromFile(@"C:soar"))
{
varext=GetExtension(img);
}补充方法:
publicstaticboolCheckImgType(stringstrImg)
{
if(strImg!=null&&strImg.ToString().Length>0)
{
inti=strImg.LastIndexOf(".");
stringStrType=strImg.Substring(i);
if(StrType==".jpg"||StrType==".gif"||StrType==".jpeg"||StrType==".png")
{
returntrue;
}
else
{
returnfalse;
}
}
else
{
returnfalse;
}
}
C#获取文件名及扩展名:
stringaFirstName=aFile.Substring(aFile.LastIndexOf("\")+1,(aFile.LastIndexOf(".")-aFile.LastIndexOf("\")-1)); //文件名
stringaLastName=aFile.Substring(aFile.LastIndexOf(".")+1,(aFile.Length-aFile.LastIndexOf(".")-1)); //扩展名
stringstrFilePaht="文件路径";
Path.GetFileNameWithoutExtension(strFilePath);这个就是获取文件名的还有的就是用Substring截取
strFilePaht.Substring(path.LastIndexOf("\")+1,path.Length-1-path.LastIndexOf("\"));
strFilePaht.Substring(path.LastIndexOf("."),path.Length-path.LastIndexOf("."));或者用openFileDialog1.SafeFileName
这样就能取到该文件的所在目录路径
stringpath1=System.IO.Path.GetDirectoryName(openFileDialog1.FileName)+@"";
stringpath=Path.GetFileName("C:MyDocumentpathimage.jpg"); //只获取文件名image.jpg
希望本文所述对大家的C#程序设计有所帮助。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短