C#判斷上傳文件是否是圖片,防止木馬上傳


方法一:用image對象判斷是否為圖片

/// <summary>
      /// 判斷文件是否為圖片
      /// </summary>
      /// <param name="path">文件的完整路徑</param>
      /// <returns>返回結果</returns>
    public Boolean IsImage(string path)
    {
        try
        {
            System.Drawing.Image img = System.Drawing.Image.FromFile(path);
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

方法二,判斷文件頭
     /// <summary>
     /// 根據文件頭判斷上傳的文件類型
     /// </summary>
    /// <param name="filePath">filePath是文件的完整路徑 </param>
     /// <returns>返回true或false</returns>
    private bool IsPicture(string filePath)
    {
        try
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(fs);
            string fileClass;
            byte buffer;
            buffer = reader.ReadByte();
            fileClass = buffer.ToString();
            buffer = reader.ReadByte();
            fileClass += buffer.ToString();
            reader.Close();
            fs.Close();
            if (fileClass == "255216" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677")

                  //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch
        {
            return false;
        }
    }

據說方法二針對常規修改的木馬有效,也就是直接修改擴展名的,比如把.asp改成.jpg這種。但是對於那種用工具生成的jpg木馬沒有效果。推薦大家用第一種好了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM