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?

4
  • 1
    Define "broken"... Also, what have you tried? Commented Mar 21, 2018 at 15:59
  • @Isma fake image such as txt file saved as image or image not displaying. Commented Mar 21, 2018 at 16:01
  • Check here stackoverflow.com/questions/15328713/… or stackoverflow.com/questions/670546/… Commented Mar 21, 2018 at 16:03
  • @Isma I will check the links, Thank you :) Commented Mar 21, 2018 at 16:05

1 Answer 1

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; } } 
Sign up to request clarification or add additional context in comments.

2 Comments

that's works brother, thank you
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.