Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path.GetExtension(file.FileName) gives possible Nullreference warning

When I add ".ToLowerInvariant()" to Path.GetExtension(file.FileName), ReSharper gives a warning for a possible Nullreference exception.

I have tried to following, but warning is nog going away. What am i missing?

if (file != null && Path.GetExtension(file.FileName) != null)
            {
                switch (Path.GetExtension(file.FileName).ToLowerInvariant())
                {
                    case ".jpg":
                    case ".png":
                    case ".gif":
                    case ".jpeg":
                        break;
                    default:
                        break;

                }
}
like image 520
Ivo Avatar asked Sep 03 '26 11:09

Ivo


1 Answers

Because ToLowerInvariant() is being called on the outcome of Path.GetExtension(). There is no guarantee that Path.GetExtension() will return anything meaningful (if file.Filename is null for example).

Best to check that the outcome of Path.GetExtension isnt null, before you call anything else on it. (or call ToLower() on file.FileName before you put it into GetExtension, either way make sure you know exactly what you're putting into GetExtension() or you cant make any guarantees that what you get out will be what you were after).

like image 182
richzilla Avatar answered Sep 05 '26 01:09

richzilla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!