BotSharp/src/Infrastructure/BotSharp.Core/Infrastructures/Streams/RealtimeTextStream.cs
2025-06-18 16:42:58 -05:00

74 lines
1.5 KiB
C#

using System.IO;
namespace BotSharp.Core.Infrastructures.Streams;
public class RealtimeTextStream : IDisposable
{
public RealtimeTextStream()
{
}
private bool _disposed = false;
private MemoryStream _contentStream = new();
public Stream? ContentStream
{
get
{
return _contentStream != null ? _contentStream : new MemoryStream();
}
}
public long Length => _contentStream.Length;
public bool IsNullOrEmpty()
{
return _contentStream == null || Length == 0;
}
public void Collect(string text)
{
if (_disposed) return;
var binary = BinaryData.FromString(text);
var bytes = binary.ToArray();
_contentStream.Position = _contentStream.Length;
_contentStream.Write(bytes, 0, bytes.Length);
_contentStream.Position = 0;
}
public string GetText()
{
if (_disposed || _contentStream.Length == 0)
{
return string.Empty;
}
var bytes = _contentStream.ToArray();
var text = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
return text;
}
public void Clear()
{
try
{
if (_disposed) return;
_contentStream.Position = 0;
_contentStream.SetLength(0);
}
catch { }
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_contentStream?.Dispose();
}
}