Check if file is image in C#

Let’s suppose you have a page on which user upload their image and you want to validate that the user is uploading the image file only not another file format. The one easy solution is to use regex and validates the extension of the file but if the user renames the extension of the file and uploads some executable code. Following is the simple c# code snippet that checks 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");

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

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru