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

Write only stream - get written bytes count with 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 - 也许它对某些人有用。

谢谢!

我制作的包装器的示例实现:

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; }
    }
}