ASP.NET中服务器端文件类型检查

Posted on 2007-11-20 22:48  海滨  阅读(404)  评论(0编辑  收藏  举报
    public static bool IsAllowExtensin(System.Web.UI.HtmlControls.HtmlInputFile hifile)//检查文件类型
    {
        System.IO.FileStream fs = new System.IO.FileStream(hifile.PostedFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); //  创建文件流对象
        System.IO.BinaryReader r = new System.IO.BinaryReader(fs);    //创建文件阅读器对象
        string fileclass = "";    //从当前文件流读取2个字节,判断文件的类型
        byte buffer;
        try
        {
            buffer = r.ReadByte();    //从当前流读取下一个字节
            fileclass = buffer.ToString();
            buffer = r.ReadByte();
            fileclass += buffer.ToString();
        }
        catch { }
        r.Close();  //关闭阅读器对象
        fs.Close();//关闭文件流
        if (fileclass == "255216" || fileclass == "7173" || fileclass == "6677" || fileclass == "13780")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
            return true;
        else
            return false;
    }

Copyright © 2024 海滨
Powered by .NET 8.0 on Kubernetes