C#从读取文本文件中读取二进制文件

时间:2011-04-05 04:03:29

标签: c# visual-studio visual-studio-2010 binaryfiles

如何使用BinaryReader修改此代码以读取二进制文件? 示例snort的日志文件?(包括文本和数字)

public string ReadFullFile()
{
    using (StreamReader streamReader = new StreamReader(this.filename))
    {
        return streamReader.ReadToEnd();
    }
}

2 个答案:

答案 0 :(得分:0)

我不知道snort的日志,但二进制阅读器是这样的:

class Record
{
    public int Id { get; set; }
    public string Name { get; set; }
}
function ReadFullFile(Action<Record> processRecord)
{
    using(var file = new FileStream("whatever.bin"))
    {
        using(var reader = new BinaryReader(file))
        {
            processRecord(new Record
            {
                Id = reader.ReadInt32(),
                Name = reader.ReadString(),
            });
        }
    }
}

答案 1 :(得分:0)

public byte[] ReadFullFile()
{
    return File.ReadAllBytes(this.FileName);
}