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?
- 1Define "broken"... Also, what have you tried?Isma– Isma2018-03-21 15:59:18 +00:00Commented Mar 21, 2018 at 15:59
- @Isma fake image such as txt file saved as image or image not displaying.AbxS– AbxS2018-03-21 16:01:09 +00:00Commented Mar 21, 2018 at 16:01
- Check here stackoverflow.com/questions/15328713/… or stackoverflow.com/questions/670546/…Isma– Isma2018-03-21 16:03:55 +00:00Commented Mar 21, 2018 at 16:03
- @Isma I will check the links, Thank you :)AbxS– AbxS2018-03-21 16:05:45 +00:00Commented Mar 21, 2018 at 16:05
Add a comment |
1 Answer
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; } }