请问各位大虾,在.net中怎么获得文件的本质类型 加入我有一个jpg的图片,把后缀名更改成了exe,应该取的文件类型还是jpg请各位给点意见,最好能有源码,谢谢!!!!! 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 有的时候需要检测上传文件的真实类型,才能准确的判断用户上传的文件是否真的是需要过滤的文件类型大多数情况下我们都是用 Path.GetExtension(file.FileName) 获取文件的扩展名,然后进行判断文件是否是我们需要过滤的文件,但是这种方法只能得到表面上的扩展名,如果一些恶作剧的用户故意把 text的文件更改为 jpg 那么Path.GetExtension(file.FileName) 获取到的文件类型就是 jpg 而不是text用下面的方法会得到文件的真实类型private bool IsAllowedExtension(HttpPostedFile hifile) {bool ret = false; System.IO.FileStream fs = new System.IO.FileStream(hifile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader r = new System.IO.BinaryReader(fs);string fileclass = "";byte buffer;try { buffer = r.ReadByte(); fileclass = buffer.ToString(); buffer = r.ReadByte(); fileclass += buffer.ToString(); }catch {return false; } r.Close(); fs.Close();/*文件扩展名说明 *7173 gif *255216 jpg *13780 png *6677 bmp *239187 txt,aspx,asp,sql *208207 xls.doc.ppt *6063 xml *6033 htm,html *4742 js *8075 xlsx,zip,pptx,mmap,zip *8297 rar *01 accdb,mdb *7790 exe,dll *5666 psd *255254 rdp *10056 bt种子 *64101 bat */ String[] fileType = { "255216", "7173", "6677", "13780", "8297", "5549", "870", "87111", "8075" };for (int i = 0; i < fileType.Length; i++) {if (fileclass == fileType[i]) { ret = true;break; } }return ret; }网上很多这样的例子http://www.google.com.hk/search?q=c%23+%E5%BE%97%E5%88%B0%E7%9C%9F%E5%AE%9E%E7%9A%84%E6%89%A9%E5%B1%95%E5%90%8D&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:zh-CN:official&client=firefox-a GridView循环显示问题? 请教:JSP页面提交表单数据到ASPX页面,中文乱码 类型转换??? GridView取值 动态加载用户控件的问题 小问题(讨论) 分离字符串问题 新装的vs 2005 中在项目添加引用后,为什么出来的窗口只有两个按钮"确定"、"取消",没有引用项目的选择框? 调用接口。 一个关于vs中创建webform的简单问题 前台循环DataTable,怎样将值赋给Label的Text属性 Online调查问卷设计
大多数情况下我们都是用 Path.GetExtension(file.FileName) 获取文件的扩展名,然后进行判断文件是否是我们需要过滤的文件,但是这种方法只能得到表面上的扩展名,如果一些恶作剧的用户故意把 text的文件更改为 jpg 那么Path.GetExtension(file.FileName) 获取到的文件类型就是 jpg 而不是text
用下面的方法会得到文件的真实类型
private bool IsAllowedExtension(HttpPostedFile hifile)
{
bool ret = false; System.IO.FileStream fs = new System.IO.FileStream(hifile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch
{
return false;
}
r.Close();
fs.Close();
/*文件扩展名说明
*7173 gif
*255216 jpg
*13780 png
*6677 bmp
*239187 txt,aspx,asp,sql
*208207 xls.doc.ppt
*6063 xml
*6033 htm,html
*4742 js
*8075 xlsx,zip,pptx,mmap,zip
*8297 rar
*01 accdb,mdb
*7790 exe,dll
*5666 psd
*255254 rdp
*10056 bt种子
*64101 bat
*/
String[] fileType = { "255216", "7173", "6677", "13780", "8297", "5549", "870", "87111", "8075" };for (int i = 0; i < fileType.Length; i++)
{
if (fileclass == fileType[i])
{
ret = true;
break;
}
}
return ret;
}网上很多这样的例子
http://www.google.com.hk/search?q=c%23+%E5%BE%97%E5%88%B0%E7%9C%9F%E5%AE%9E%E7%9A%84%E6%89%A9%E5%B1%95%E5%90%8D&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:zh-CN:official&client=firefox-a