我有一个固定记录长度为 100 的二进制文件,并希望使用以下代码读取文件中的所有记录:
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
:
你调用的对象是空的。