C#獲取圖片文件擴展名的方法
更新時間:2014年10月28日 16:15:13 投稿:shichen2014
這篇文章主要介紹了C#獲取圖片文件擴展名的方法,實例總結(jié)了較為常見的獲取圖片文件擴展名的技巧,非常具有實用價值,需要的朋友可以參考下
下面我給各位朋友整理了一篇C# 獲取圖片文件擴展名的例子,這里方法都非常的簡單,我們只用到了image.RawFormat.Guid就實現(xiàn)了,具體看代碼
例子
復(fù)制代碼 代碼如下:
/// <summary>
/// 根據(jù)圖像獲取圖像的擴展名
/// </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();
}
/// 根據(jù)圖像獲取圖像的擴展名
/// </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();
}
使用方法如下:
復(fù)制代碼 代碼如下:
using (var img = Image.FromFile(@"C:soar"))
{
var ext = GetExtension(img);
}
{
var ext = GetExtension(img);
}
補充方法:
復(fù)制代碼 代碼如下:
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;
}
}
{
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# 獲取文件名及擴展名:
復(fù)制代碼 代碼如下:
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);這個就是獲取文件名的
string aLastName = aFile.Substring(aFile.LastIndexOf(".") + 1, (aFile.Length - aFile.LastIndexOf(".") - 1)); //擴展名
string strFilePaht="文件路徑";
Path.GetFileNameWithoutExtension(strFilePath);這個就是獲取文件名的
還有的就是用Substring截取
復(fù)制代碼 代碼如下:
strFilePaht.Substring(path.LastIndexOf("\") + 1, path.Length - 1 - path.LastIndexOf("\"));
strFilePaht.Substring(path.LastIndexOf("."), path.Length - path.LastIndexOf("."));
strFilePaht.Substring(path.LastIndexOf("."), path.Length - path.LastIndexOf("."));
或者用openFileDialog1.SafeFileName
這樣就能取到該文件的所在目錄路徑
復(fù)制代碼 代碼如下:
string path1 = System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + @"";
string path = Path.GetFileName("C:My Documentpathimage.jpg"); //只獲取文件名image.jpg
string path = Path.GetFileName("C:My Documentpathimage.jpg"); //只獲取文件名image.jpg
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
C# Char結(jié)構(gòu)中IsLetterOrDigit(Char)的方法詳解
這篇文章給大家介紹了C#的Char 結(jié)構(gòu)的IsLetterOrDigit(Char)的方法,并通過代碼示例給大家介紹的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下2024-02-02

