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?
Asked
Active
Viewed 362 times
0

m7mdabuodeh
- 23
- 9
-
1Define "broken"... Also, what have you tried? – Isma Mar 21 '18 at 15:59
-
@Isma fake image such as txt file saved as image or image not displaying. – m7mdabuodeh Mar 21 '18 at 16:01
-
Check here https://stackoverflow.com/questions/15328713/determine-whether-a-file-is-a-valid-image-format or https://stackoverflow.com/questions/670546/determine-if-file-is-an-image#670549 – Isma Mar 21 '18 at 16:03
-
@Isma I will check the links, Thank you :) – m7mdabuodeh Mar 21 '18 at 16:05
1 Answers
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
-
-
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