c#如何获取文件扩展名?c#取得图片文件扩展名的例子

发布时间:2020-07-22编辑:脚本学堂
c#如何获取图片文件扩展名?一个c#获取图片文件扩展名的实例代码,使用image.RawFormat.Guid取得文件扩展名。

c# 获取图片文件扩展名,使用image.RawFormat.Guid实现。

1、代码:
 

复制代码 代码示例:
/// <summary>
/// 根据图像获取图像的扩展名
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static String GetExtension(Image image)
{
foreach (var pair in ImageFormats)
{
if (pair.Value.Guid == image.RawFormat.Guid)
{
return pair.Key;
}
}
throw new BadImageFormatException();
}

使用方法:
 

using (var img = Image.FromFile(@"C:soar"))
{
var ext = GetExtension(img);
}

补充方法:
 

复制代码 代码示例:
public static bool CheckImgType(string strImg)
{
if(strImg!=null&&strImg.ToString().Length>0)
{
int i = strImg.LastIndexOf(".");
string StrType = strImg.Substring(i);
if (StrType == ".jpg" || StrType == ".gif" || StrType == ".jpeg" || StrType == ".png")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}

2、c#获取文件名及扩展名
 

复制代码 代码示例:
string aFirstName = aFile.Substring(aFile.LastIndexOf("") + 1, (aFile.LastIndexOf(".") - aFile.LastIndexOf("") - 1));  //文件名
string aLastName = aFile.Substring(aFile.LastIndexOf(".") + 1, (aFile.Length - aFile.LastIndexOf(".") - 1));   //扩展名
string strFilePaht="文件路径";
Path.GetFileNameWithoutExtension(strFilePath);这个就是获取文件名的

3、substring截取文件扩展名
 

复制代码 代码示例:
strFilePaht.Substring(path.LastIndexOf("") + 1, path.Length - 1 - path.LastIndexOf(""));
strFilePaht.Substring(path.LastIndexOf("."), path.Length - path.LastIndexOf("."));

4、或用openFileDialog1.SafeFileName,取到该文件的所在目录路径
 

复制代码 代码示例:
string path1 = System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + @"";
string path = Path.GetFileName("C:My Documentpathimage.jpg");//只获取文件名image.jpg