BotSharp/src/Infrastructure/BotSharp.Core/Infrastructures/Streams/RealtimeTextStream.cs

74 lines
1.5 KiB
C#
Raw Normal View History

2025-05-14 23:14:01 +00:00
using System.IO;
2025-06-18 21:42:58 +00:00
namespace BotSharp.Core.Infrastructures.Streams;
2025-05-14 23:14:01 +00:00
2025-06-18 21:42:58 +00:00
public class RealtimeTextStream : IDisposable
2025-05-14 23:14:01 +00:00
{
2025-06-18 21:42:58 +00:00
public RealtimeTextStream()
2025-05-14 23:14:01 +00:00
{
2025-06-18 21:42:58 +00:00
2025-05-14 23:14:01 +00:00
}
2025-05-19 19:54:40 +00:00
private bool _disposed = false;
2025-05-14 23:14:01 +00:00
private MemoryStream _contentStream = new();
public Stream? ContentStream
{
get
{
return _contentStream != null ? _contentStream : new MemoryStream();
}
}
2025-06-18 21:42:58 +00:00
public long Length => _contentStream.Length;
public bool IsNullOrEmpty()
{
return _contentStream == null || Length == 0;
}
2025-05-14 23:14:01 +00:00
public void Collect(string text)
{
2025-05-19 19:54:40 +00:00
if (_disposed) return;
2025-05-14 23:14:01 +00:00
var binary = BinaryData.FromString(text);
var bytes = binary.ToArray();
_contentStream.Position = _contentStream.Length;
_contentStream.Write(bytes, 0, bytes.Length);
_contentStream.Position = 0;
}
2025-05-15 04:49:36 +00:00
public string GetText()
2025-05-14 23:14:01 +00:00
{
2025-05-19 19:54:40 +00:00
if (_disposed || _contentStream.Length == 0)
2025-05-14 23:14:01 +00:00
{
return string.Empty;
}
var bytes = _contentStream.ToArray();
var text = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
return text;
}
public void Clear()
{
2025-05-19 19:54:40 +00:00
try
{
if (_disposed) return;
_contentStream.Position = 0;
_contentStream.SetLength(0);
}
catch { }
2025-05-14 23:14:01 +00:00
}
public void Dispose()
{
2025-05-19 19:54:40 +00:00
if (_disposed) return;
_disposed = true;
2025-05-14 23:14:01 +00:00
_contentStream?.Dispose();
}
}