How to take a stringbuilder and convert it to a streamReader? - c#

How to take a stringbuilder and convert it to a stream?
SO my stringbuilder has to be converted into a :
StreamReader stream = ????
Update
I tried using a stringreader like:
StringReader sr = new StringReader(sb.ToString());
StreamReader stream = new StreamReader(sr);
but that doesn't work?

Use ToString to convert the StringBuilder into a String, and use a StringReader to wrap the String as a Stream.

If using a StreamReader is a requirement then convert the string to a memory stream and then create a new StreamReader using that object:
StreamReader reader= new StreamReader(
new MemoryStream(Encoding.ASCII.GetBytes(sb.ToString())));

Related

Is it ok to handle text file by Streamreader & StreamWriter without prior use of FileStream?

Is it still good practise to handle the text file withot using FileStream like in an example below:
StreamWriter sw2 = new StreamWriter(filePath);
sw2.WriteLine("Some text");
sw2.Close();
StreamReader sr2= new StreamReader(filePath);
string text =sr2.ReadToEnd();
Console.WriteLine(text);
sr2.Close();
Or it is much better to use FileStream class first:
string filePath= #"C:\Users\Dom\OneDrive\CODE\Temp29-01-2021\TextFile1.txt";
FileStream fs = new FileStream(filePath,FileMode.Create);
StreamWriter sw= new StreamWriter(fs);
foreach (var item in list)
sw.WriteLine("Some text");
sw.Close();
fs =new FileStream(filePath, FileMode.Open);
string line;
StreamReader sr = new StreamReader(fs);
while ((line=sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
sr.Close();
Is it better to use it with FileStream, if so why?
Is it better to use with FileStram for asynchronous operations?
And the last question is : if we use FileStream class for writing and reading from hte same file,
do we have to always create two seperate instances of FileStream - one for writing and another for reading from specified text file?

Usage of StreamReader in C#

I want to read a file data.json and convert it to a string.
My code is this one:
String json = null;
using (StreamReader sr = new StreamReader("data.json"))
{
json = sr.ReadToEnd();
}
but Visual Studio tells me that StreamReader does not expect a String as constructor argument.
How can I tell StreamReader that I want to read the file data.json?
Actually StreamReader supports constructor which accepts file path for most platforms, but not all. But anyway - simply use File.ReadAllText:
string json = File.ReadAllText("data.json");
It creates StreamReader internally (link to source):
using (var sr = new StreamReader(path, encoding))
return sr.ReadToEnd();
UPDATE: You can always pass stream to StreamReader. Use FileStream to open stream for reading file, and then pass it to StreamReader:
string json = null;
using (var stream = new FileStream("data.json", FileMode.Open))
using (var reader = new StreamReader(stream))
json = reader.ReadToEnd();

Convert String to System.IO.Stream [duplicate]

This question already has answers here:
How do I generate a stream from a string?
(12 answers)
Closed 9 years ago.
I need to convert a String to System.IO.Stream type to pass to another method.
I tried this unsuccessfully.
Stream stream = new StringReader(contents);
Try this:
// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);
and
// convert stream to string
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
To convert a string to a stream you need to decide which encoding the bytes in the stream should have to represent that string - for example you can:
MemoryStream mStrm= new MemoryStream( Encoding.UTF8.GetBytes( contents ) );
MSDN references:
http://msdn.microsoft.com/en-us/library/ds4kkd55%28v=VS.100%29.aspx
http://msdn.microsoft.com/en-us/library/e55f3s5k.aspx
System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));
string str = "asasdkopaksdpoadks";
byte[] data = Encoding.ASCII.GetBytes(str);
MemoryStream stm = new MemoryStream(data, 0, data.Length);
this is old but for help :
you can also use the stringReader stream
string str = "asasdkopaksdpoadks";
StringReader TheStream = new StringReader( str );

Serializing a memorystream object to string

Right now I'm using XmlTextWriter to convert a MemoryStream object into string. But I wan't to know whether there is a faster method to serialize a memorystream to string.
I follow the code given here for serialization - http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp
Edited
Stream to String
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
string content = sr.ReadToEnd();
SaveInDB(ms);
}
String to Stream
string content = GetFromContentDB();
byte[] byteArray = Encoding.ASCII.GetBytes(content);
MemoryStream ms = new MemoryStream(byteArray);
byte[] outBuf = ms.GetBuffer(); //error here
using(MemoryStream stream = new MemoryStream()) {
stream.Position = 0;
var sr = new StreamReader(stream);
string myStr = sr.ReadToEnd();
}
You cant use GetBuffer when you use MemoryStream(byte[]) constructor.
MSDN quote:
This constructor does not expose the
underlying stream. GetBuffer throws
UnauthorizedAccessException.
You must use this constructor and set publiclyVisible = true in order to use GetBuffer
In VB.net i used this
Dim TempText = System.Text.Encoding.UTF8.GetString(TempMemoryStream.ToArray())
in C# may apply

Xml Serialization / Deserialization Problem

After writing and reading an xml string to and from a stream, it ceases to be deserializable. The new string is clipped.
string XmlContent = getContentFromMyDataBase();
XmlSerializer xs = new XmlSerializer(typeof(MyObj));
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
char[] ca = XmlContent.ToCharArray(); // still working up to this point.
ms.Position = 0;
sw.Write(ca);
StreamReader sr = new StreamReader(ms);
ms.Position = 0;
string XmlContentAgain = sr.ReadToEnd();
Console.WriteLine(XmlContentAgain); // (outputstring is too short.)
MyObj theObj = (MyObj)xs.Deserialize(ms); // Can't deserialize.
Any suggestions as to how to fix this or what is causing the problem? My only guess is that there is some form of encoding issue, but I wouldn't know how to go about finding/fixing it.
Additionally, myObj has a generic dictionary member, which typically isn't serializable, so I have stolen code from Paul Welter in order to serialize it.
Try flushing and disposing or even better simplify your code using a StringReader:
string xmlContent = getContentFromMyDataBase();
var xs = new XmlSerializer(typeof(MyObj));
using (var reader = new StringReader(xmlContent))
{
var theObj = (MyObj)xs.Deserialize(reader);
}
Note: The getContentFromMyDataBase method also suggests that you are storing XML in your database that you are deserializing back to an object. Don't.
You need to Flush or Close (closing implicitly flushes) the StreamWriter, or you cannot be sure it is done writing to the underlying stream. This is because it is doing some internal buffering.
Try this:
using(StreamWriter sw = new StreamWriter(ms))
{
char[] ca = XmlContent.ToCharArray(); // still working up to this point.
ms.Position = 0;
sw.Write(ca);
}
StreamReader sr = new StreamReader(ms);
ms.Position = 0;
string XmlContentAgain = sr.ReadToEnd();

Categories