判断文件格式

判断非文本文件格式:

public static bool IsAllowedExtension(FileUpload hifile)
    {
        Stream fs = hifile.PostedFile.InputStream;
        BinaryReader r = new BinaryReader(fs);
        string fileclass = "";
        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")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar,208207是doc/xls
        {
            return true;
        }
        else
        {
            return false;
        }

    }

判断文件方式:
    public static bool IsTextFile(FileUpload hifile)
    { 
        //要比对的字节,越大,正确度越高,但32个只够了. 
        char[]buf = new char[32];  //实际读到的字符数 
        int readint = 0;
        try
        {
            StreamReader reader = new StreamReader(hifile.PostedFile.InputStream);  
            //最多读 buf.Length 个字符   
            readint = reader.ReadBlock(buf, 0, buf.Length);   
            reader.Close();    //比对是否存在 '\0' 这个字符   
            for (int i = 0; i < readint; i++)   
            {    
                if (buf[i] == '\0')     
                {
                    return false;    //存在:这个就不是文本文件  
                }  
            }    //没找到,那么很大概率是文本文件  
            return true;             
        }
        catch (IOException ex) 
        {
            Console.WriteLine(ex.Message);
        }
        return false;
    }

posted @   94cool  阅读(249)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
< 2009年6月 >
31 1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 1 2 3 4
5 6 7 8 9 10 11
点击右上角即可分享
微信分享提示