下面我給各位朋友整理了一篇C# 獲取圖片文件擴展名的例子,這里方法都非常的簡單,我們只用到了image.RawFormat.Guid就實現了,具體看代碼
例子
/// <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;
}
}
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);這個就是獲取文件名的
還有的就是用Substring截取
strFilePaht.Substring(path.LastIndexOf("/") + 1, path.Length - 1 - path.LastIndexOf("/"));
strFilePaht.Substring(path.LastIndexOf("."), path.Length - path.LastIndexOf("."));
或者用openFileDialog1.SafeFileName
這樣就能取到該文件的所在目錄路徑
string path1 = System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + @"";
string path = Path.GetFileName("C:My Documentpathimage.jpg"); //只獲取文件名image.jpg
希望本文所述對大家的C#程序設計有所幫助。