Re: BinaryFormatter отловить EndOfStream
От: Свободу Анжеле Девис и Юрию Деточкину СССР  
Дата: 05.12.24 09:35
Оценка: 4 (1) +2
public class TrackingStream : Stream
{
    private readonly Stream _innerStream;
    public bool IsEndOfStream { get; private set; }

    public TrackingStream(Stream innerStream)
    {
        _innerStream = innerStream;
        IsEndOfStream = false;
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        int bytesRead;
        try
        {
            bytesRead = _innerStream.Read(buffer, offset, count);
            if (bytesRead == 0)
            {
                IsEndOfStream = true;
            }
        }
        catch (IOException)
        {
            IsEndOfStream = true;
            throw;
        }
        return bytesRead;
    }

    // Implement other abstract members by delegating to _innerStream
    public override bool CanRead => _innerStream.CanRead;
    public override bool CanSeek => _innerStream.CanSeek;
    public override bool CanWrite => _innerStream.CanWrite;
    public override long Length => _innerStream.Length;

    public override long Position
    {
        get => _innerStream.Position;
        set => _innerStream.Position = value;
    }

    public override void Flush() => _innerStream.Flush();
    public override long Seek(long offset, SeekOrigin origin) => _innerStream.Seek(offset, origin);
    public override void SetLength(long value) => _innerStream.SetLength(value);
    public override void Write(byte[] buffer, int offset, int count) => _innerStream.Write(buffer, offset, count);
}



var trackingStream = new TrackingStream(stream);
try
{
    var msg = _serializer.Deserialize(trackingStream);
}
catch (SerializationException ex)
{
    if (trackingStream.IsEndOfStream)
    {
        // Handle EndOfStream scenario
    }
    else
    {
        // Handle other serialization errors
    }
}
Нет времени на раскачку!
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.