在網上查了好多資料,大部分都是通過將文件讀成二進制流,取前兩個字節判斷,比如.jpg的是255216.代碼如下:
/// <summary>
/// Checks the file is textfile or not.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns></returns>
public static FileExtension CheckTextFile(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
string fileType = string.Empty; ;
try
{
byte data = br.ReadByte();
fileType += data.ToString();
data = br.ReadByte();
fileType += data.ToString();
FileExtension extension;
try
{
extension = (FileExtension)Enum.Parse(typeof(FileExtension), fileType);
}
catch
{
extension=FileExtension.VALIDFILE
}
return extension;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
{
fs.Close();
br.Close();
}
}
}
}
public enum FileExtension
{
JPG = 255216,
GIF = 7173,
PNG = 13780,
SWF = 6787,
RAR = 8297,
ZIP = 8075,
_7Z = 55122,
VALIDFILE=9999999
// 255216 jpg;
// 7173 gif;
// 6677 bmp,
// 13780 png;
// 6787 swf
// 7790 exe dll,
// 8297 rar
// 8075 zip
// 55122 7z
// 6063 xml
// 6033 html
// 239187 aspx
// 117115 cs
// 119105 js
// 102100 txt
// 255254 sql
} <