How to check stream has Image or not

Let's suppose you have a page on which user upload there image and you want to validate that user is uploading image file only not other file format.The one easy solution is use regex and validate the extension of the file but if user rename the extension of the file and upload some executable code.Following is the simple c# code snippet that check the file type by the header value.

private bool IsImage()
        bool isImage = false;
        FileStream stream = new FileStream(Server.MapPath(@"Images\a.txt"), FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(stream);
        // Read the first 25 characters, we will be checking for a GIF or JPG signature.
        char[] strBuffer = new char[25];
        reader.ReadBlock(strBuffer, 0, 25);
        string stringBuffer = new string(strBuffer);
        // Is this an image?
        if (stringBuffer.IndexOf("GIF8") > -1 || stringBuffer.IndexOf("JFIF") > -1)
            isImage = true;
            Response.Write("It's an image");

            Response.Write("It's HTML or other junk.");
        return isImage;

Post a Comment


Close Menu