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

问题描述 投票:0回答:2

考虑我有以下片段:

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 - 也许它对某人有用。

谢谢!

c# stream datacontractserializer
2个回答
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; }
    }
}

0
投票

可与:

一起使用
Stream.Position

希望我能理解你,这会对你有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.