即使重命名扩展名也要阻止exe上传 [英] Prevent an exe from being uploaded even after renaming its extention

查看:170
本文介绍了即使重命名扩展名也要阻止exe上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 c#在asp.net上工作.

I am working on asp.net with c#.

我的表单中有一个文件上传控件.一切正常.

There is a file upload control in my form. Everything is working fine.

问题在于,只需重命名即可上传 .exe 文件.我还想限制大小.

The problem is that an .exe file can be uploaded by just renaming it. I would also like to restrict the size.

推荐答案

在您的情况下,最好的方法是检查文件的第一个字节以确定它们是什么.

best way in your case is check the first bytes of the file to determine what they are.

您应该使用 FindMimeFromData函数根据提供的数据确定MIME类型.

you should use FindMimeFromData function to determines the MIME type from the data provided.

看看文件签名表

and at this SO answer that shows you how get mime type without using extension.

此处有一个带有文件签名列表的表

Here there is a table with List of file signatures

exe 文件具有十六进制签名 4D 5A (以ASCII表示, 0x5A4D MZ )

exe files have hex signature 4D 5A (In ASCII representation, 0x5A4D is MZ)

从这一点上讲,我们可以执行此功能

from this point we can do this function

    public static bool IsExecutable(string filePath)
    {            
      var firstBytes = new byte[2];
      using (var fileStream = File.Open(filePath, FileMode.Open))
      {
          fileStream.Read(firstBytes, 0, 2);
      }
      return Encoding.UTF8.GetString(firstBytes) == "MZ";
    }

这篇关于即使重命名扩展名也要阻止exe上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆