using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace WebApplication1.UserControl
{
public partial class FileExtension : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FileExt filetype = CheckExtension(@"C:\Users\**\Desktop\壁纸2");
if (filetype == FileExt.PNG ||
filetype == FileExt.JPG ||
filetype == FileExt.GIF)
{
Response.Write("这是一张图片,后缀为:" + filetype.ToString());
}
else
{
Response.Write("非法文件");
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!this.FileUpload1.HasFile)
{
return;
}
System.IO.Stream fileStream;
int FileLen;
FileLen = this.FileUpload1.PostedFile.ContentLength;
// 读取文件的 byte[]
byte[] bytes = new byte[FileLen];
fileStream = this.FileUpload1.PostedFile.InputStream;
fileStream.Read(bytes, 0, FileLen);
fileStream.Seek(0, SeekOrigin.Begin);
FileExt filetype = CheckExtension(fileStream);
if (filetype == FileExt.PNG ||
filetype == FileExt.JPG ||
filetype == FileExt.GIF)
{
Response.Write("这是一张图片,后缀为:" + filetype.ToString());
}
else
{
Response.Write("非法文件");
}
}
/// Checks the file is textfile or not.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <returns></returns>
public static bool CheckIsTextFile(string fileName)
{
System.IO.FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
bool isTextFile = true;
try
{
int i = 0;
int length = (int)fs.Length;
byte data;
while (i < length && isTextFile)
{
data = (byte)fs.ReadByte();
isTextFile = (data != 0);
i++;
}
return isTextFile;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}
public static FileExt CheckExtension(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
return CheckExtension(fs);
}
public static FileExt CheckExtension(Stream fs)
{
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();
FileExt extension;
try
{
extension = (FileExt)Enum.Parse(typeof(FileExt), fileType);
}
catch
{
extension = FileExt.VALIDFILE;
}
return extension;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (fs != null)
{
fs.Close();
br.Close();
}
}
}
}
}
public enum FileExt
{
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
}