只写流 - 使用DataContractSerializer获取写入的字节数

时间:2015-05-22 13:09:30

标签: c# stream datacontractserializer

考虑我有以下代码段:

public void Store(Stream s, object t)
{
    var serializer = new DataContractSerializer(target.GetType(),
                                            new DataContractSerializerSettings
                                            {
                                                PreserveObjectReferences = true
                                            });

    serializer.WriteObject(s, target);
}

其中s 只写不支持搜索

有没有办法获得WriteObject写入流的字节数?我知道我可以通过以下方式实现:

using (var memStream = new MemoryStream())
{
    serializer.WriteObject(serializer, target);
    Debug.WriteLine(memStream.Length);
    memStream.CopyTo(s);
}

但我想知道有可能避免CopyTo - 对象非常庞大。

修改 我想出了一个想法:我可以创建一个在写入时计算字节数的包装器。它是如此肥胖的最佳解决方案,但也许还有另一种方式。

完成

我已经实现了一个包装器:https://github.com/pwasiewicz/counted-stream - 也许对某人有用。

谢谢!

1 个答案:

答案 0 :(得分:0)

我做过的包装器的示例实现:

public class CountedStream : Stream
{
    private readonly Stream stream;
    public CountedStream(Stream stream)
    {
        if (stream == null) throw new ArgumentNullException("stream");

        this.stream = stream;
    }

    public long WrittenBytes { get; private set; }

    public override void Flush()
    {
        this.stream.Flush();
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        return this.stream.Read(buffer, offset, count);
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        return this.stream.Seek(offset, origin);
    }

    public override void SetLength(long value)
    {
        this.stream.SetLength(value);
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        if (buffer.Length >= offset + count)
                     throw new ArgumentException("Count exceeds buffer size");
        this.stream.Write(buffer, offset, count);
        this.WrittenBytes += count;
    }

    public override bool CanRead
    {
        get { return this.stream.CanRead; }
    }

    public override bool CanSeek
    {
        get { return this.stream.CanSeek; }
    }

    public override bool CanWrite
    {
        get { return this.stream.CanWrite; }
    }

    public override long Length
    {
        get { return this.stream.Length; }
    }

    public override bool CanTimeout
    {
        get { return this.stream.CanTimeout; }
    }

    public override long Position
    {
        get { return this.stream.Position; }
        set { this.stream.Position = value; }
    }
}