I have an asp.net/C# class that resizes images for caching on the server as files, however the portion of the code that determines which encoder to use seems to occasionally throw a NullReferenceException.
Here is the code which initializes and passes back the encoders:
public static class ImageUtilities{
private static Dictionary<string, ImageCodecInfo> encoders = null;
public static Dictionary<string, ImageCodecInfo> Encoders{
get{
if (encoders == null){
encoders = new Dictionary<string, ImageCodecInfo>();
}
//if there are no codecs, try loading them
if (encoders.Count == 0){
foreach (ImageCodecInfo codec in ImageCodecInfo.GetImageEncoders()){
encoders.Add(codec.MimeType.ToLower(), codec);
}
}
return encoders;
}
}
...
This is the specific line the exception is being thrown on:
encoders.Add(codec.MimeType.ToLower(), codec);
This is the error text:
Object reference not set to an instance of an object.
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
This is the only place where the Encoders property is called (and subsequently is the line below that one in the stack trace):
if (Encoders.ContainsKey(lookupKey)){
foundCodec = Encoders[lookupKey];
}
Even if lookupKey were null, shouldn't the lookup just return null rather than throwing an exception?