0
我有100固定記錄長度的二進制文件,並想讀取文件中的所有記錄,此代碼的所有項目的IEnumerable:返回與迭代
public IEnumerable<Book> GetAll()
{
Book book;
using (Stream st = File.Open(HttpContext.Current.Server.MapPath("/") + "library.majid", FileMode.OpenOrCreate, FileAccess.Read))
{
long len = st.Length;
using (BinaryReader reader = new BinaryReader(st))
{
for (int i = 0; i < len/100; i++)
{
st.Position = i * 100;
if (!reader.ReadBoolean())
yield return null;
book = new Book()
{
Id = reader.ReadInt32(),
Name = reader.ReadString(),
Dewey = reader.ReadString()
};
try
{
book.Subject = reader.ReadString();
book.RegDate = reader.ReadInt32();
book.PubDate = reader.ReadInt32();
}
catch (EndOfStreamException) { }
yield return book;
}
}
}
}
public static DataTable ListBooks(this IEnumerable<classes.Book> objs)
{
DataTable table = new DataTable();
table.Columns.Add("id",typeof(int));
table.Columns.Add("name",typeof(String));
table.Columns.Add("dewey", typeof(String));
table.Columns.Add("subject", typeof(String));
table.Columns.Add("reg");
table.Columns.Add("pub");
var values = new object[6];
if (objs != null)
foreach (classes.Book item in objs)
{
values[0] = item.Id;
values[1] = item.Name;
values[2] = item.Dewey;
values[3] = item.Subject;
values[4] = ((DateTime)IntToDateTime(item.RegDate)).ToLongDateString();
if (item.PubDate != null)
values[5] = IntToDateTime(item.PubDate);
else
values[5] = "";
table.Rows.Add(values);
}
return table;
}
,當我想用用結果與ListBooks(GetAll())
我在foreach
的第一行看到此錯誤:
未將對象引用設置爲對象的實例。