0

I am using FileUpload control on my ASP.NET C# application, for purpose of uploading images file and I want to check if the uploaded image is broken or not.

My application checks the extensions and it works fine, but if I uploads fake image file (such as txt file saved as image file) the server accept it.

My question in short is How to prevent that?

1 Answers1

1

As @Isma commented, define "broken".

But you can try to create a new System.Drawing.Image with it. If you want to validate anything else about it, then access it's properties. For instance you can check that the image is larger than 1 pixel if that suits your purpose. If an exception is thrown creating, or during your other checks, then it is (unlikely) a valid image.

    private static bool CheckImage(string filename)
    {
        try
        {
            using (var image = Image.FromFile(filename))
            {
                if(image.Height<2 && image.Width<2)
                    return false
            }
            return true;
        }
        catch (Exception ex)
        {
            // probably should log more information here
            return false;
        }
    }
hometoast
  • 11,522
  • 5
  • 41
  • 58
  • that's works brother, thank you – m7mdabuodeh Mar 21 '18 at 16:09
  • private bool GetImageSize(Stream file) { try { System.Drawing.Image img = System.Drawing.Image.FromStream(file); return true; } catch(Exception ex) { return false; } } This another answer worked for me – m7mdabuodeh Mar 21 '18 at 19:23