获取NullRefrenceException未按用户代码处理

时间:2013-07-05 18:23:10

标签: c# .net

我在第_dict.Add(id, ar)行收到以下错误:

  

对象引用未设置为对象的实例

这是我的代码:

public Dictionary<int, byte[]> _dict;

public IDictionary<int, byte[]> dict()
{
    string sp = HttpContext.Current.Server.MapPath("Images");
    DirectoryInfo folder = new DirectoryInfo(sp);
    FileInfo[] files = folder.GetFiles("*.jpg");
    foreach (var file in files)
    {
        string name = file.Name;
        int id = Convert.ToInt32(name.Substring(0, name.Length - 4));
        FileStream fS = new FileStream(sp + "\\" + name, FileMode.Open, FileAccess.Read);
        byte[] ar = new byte[fS.Length];
        fS.Read(ar, 0, (int)fS.Length);
        fS.Close();
        _dict.Add(id, ar);
    }
    return _dict;
}

1 个答案:

答案 0 :(得分:6)

_dict从未被实例化过。改变它如此:

public Dictionary<int, byte[]> _dict = new Dictionary<int, byte[]>();