如何检查流是否在文本字段的末尾?

时间:2019-07-02 10:25:14

标签: c#

我正在写一个固定长度的文件阅读器。我已经建立了一个Attribute类,用于定义文件中每个字段的索引和长度:

[AttributeUsage(AttributeTargets.Field)]
public class FixedAttribute : Attribute
{
    public int Index { get; private set; }
    public int Length { get; private set; }

    public FixedAttribute(int index, int length)
    {
        this.Index = index;
        this.Length = length;
    }
}

还有Reader类:

public class FixedReader
{
    private readonly Stream stream;
    private byte[] buffer;

    public FixedReader(Stream stream)
    {
        this.stream = stream;
        this.buffer = new byte[4];
    }

    public void Read<T>(T data)
    {
        var fields = typeof(T).GetFields();

        foreach (var field in fields)
        {
            var attrib = field.GetCustomAttribute(typeof(FixedAttribute)) as FixedAttribute;
            if (attrib == null)
                continue;

            stream.Seek(attrib.Index, SeekOrigin.Begin);
            if (buffer.Length < attrib.Length)
            {
                buffer = new byte[attrib.Length];
            }
            stream.Read(buffer, 0, attrib.Length);

            //Here the parsing...
        }
    }
}

当前Read方法返回void。但我希望它返回bool,以便可以将类实现为:

var reader = new FixedReader(myStream);
var myData = new MyData();

while (reader.Read()) {}

如何在Read方法中以及在何处添加EOF检查?

0 个答案:

没有答案