I want to be able to build a string from a class that I create that derives from Stream
. Specifically, I want to be able to write code like this:
void Print(Stream stream) {
// Some code that operates on a Stream.
}
void Main() {
StringStream stream = new StringStream();
Print(stream);
string myString = stream.GetResult();
}
Can I create a class called StringStream
that makes this possible? Or is such a class already available?
Update: In my example, the method Print
is provided in a third-party external DLL. As you can see, the argument that Print
expects is a Stream
. After printing to the Stream
, I want to be able to retrieve its content as a string.
This question is related to
c#
.net
stringstream
You can create a MemoryStream from a String and use that in any third-party function that requires a stream. In this case, MemoryStream, with the help of UTF8.GetBytes, provides the functionality of Java's StringStream.
String content = "stuff";
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)))
{
Print(stream); //or whatever action you need to perform with the stream
stream.Seek(0, SeekOrigin.Begin); //If you need to use the same stream again, don't forget to reset it.
UseAgain(stream);
}
stream.Seek(0, SeekOrigin.Begin);
string s;
using (var readr = new StreamReader(stream))
{
s = readr.ReadToEnd();
}
//and don't forget to dispose the stream if you created it
I see a lot of good answers here, but none that directly address the lack of a StringStream class in C#. So I have written one of my own...
public class StringStream : Stream
{
private readonly MemoryStream _memory;
public StringStream(string text)
{
_memory = new MemoryStream(Encoding.UTF8.GetBytes(text));
}
public StringStream()
{
_memory = new MemoryStream();
}
public StringStream(int capacity)
{
_memory = new MemoryStream(capacity);
}
public override void Flush()
{
_memory.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _memory.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _memory.Seek(offset, origin);
}
public override void SetLength(long value)
{
_memory.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
_memory.Write(buffer, offset, count);
return;
}
public override bool CanRead => _memory.CanRead;
public override bool CanSeek => _memory.CanSeek;
public override bool CanWrite => _memory.CanWrite;
public override long Length => _memory.Length;
public override long Position
{
get => _memory.Position;
set => _memory.Position = value;
}
public override string ToString()
{
return System.Text.Encoding.UTF8.GetString(_memory.GetBuffer(), 0, (int) _memory.Length);
}
public override int ReadByte()
{
return _memory.ReadByte();
}
public override void WriteByte(byte value)
{
_memory.WriteByte(value);
}
}
An example of its use...
string s0 =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor\r\n" +
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud\r\n" +
"exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\r\n" +
"in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint\r\n" +
"occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\r\n";
StringStream ss0 = new StringStream(s0);
StringStream ss1 = new StringStream();
int line = 1;
Console.WriteLine("Contents of input stream: ");
Console.WriteLine();
using (StreamReader reader = new StreamReader(ss0))
{
using (StreamWriter writer = new StreamWriter(ss1))
{
while (!reader.EndOfStream)
{
string s = reader.ReadLine();
Console.WriteLine("Line " + line++ + ": " + s);
writer.WriteLine(s);
}
}
}
Console.WriteLine();
Console.WriteLine("Contents of output stream: ");
Console.WriteLine();
Console.Write(ss1.ToString());
Since your Print() method presumably deals with Text data, could you rewrite it to accept a TextWriter
parameter?
The library provides a StringWriter: TextWriter
but not a StringStream. I suppose you could create one by wrapping a MemoryStream, but is it really necessary?
After the Update:
void Main()
{
string myString; // outside using
using (MemoryStream stream = new MemoryStream ())
{
Print(stream);
myString = Encoding.UTF8.GetString(stream.ToArray());
}
...
}
You may want to change UTF8 to ASCII, depending on the encoding used by Print().
You can use a StringWriter to write values to a string. It provides a stream-like syntax (though does not derive from Stream
) which works with an underlying StringBuilder
.
You have a number of options:
One is to not use streams, but use the TextWriter
void Print(TextWriter writer)
{
}
void Main()
{
var textWriter = new StringWriter();
Print(writer);
string myString = textWriter.ToString();
}
It's likely that TextWriter
is the appropriate level of abstraction for your print
function.
Streams are aimed at writing binary data, while TextWriter works at a higher abstraction level, specifically geared towards outputting strings.
If your motivation is that you also want your Print
function to write to files, you can get a text writer from a filestream as well.
void Print(TextWriter writer)
{
}
void PrintToFile(string filePath)
{
using(var textWriter = new StreamWriter(filePath))
{
Print(writer);
}
}
If you REALLY want a stream you can look at MemoryStream
.
Source: Stackoverflow.com