StringBuilder and StreamReader
Hello,
I have code:
StringBuilder data = new StringBuilder();
StreamReader st = new StreamReader(Utility.FileName(ObjectToLoad));
while (!st.EndOfStream)
{
data.Append(st.ReadLine());
}
st.BaseStream.Close();
st.Close();
st.Dispose();
returnObject = DeserializeObject(data.ToString(), ObjectToLoad);
private static Object DeserializeObject(String pXmlizedString, Type ObjectToLoad)
{
XmlSerializer xs = new XmlSerializer(ObjectToLoad);
MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
return xs.Deserialize(memoryStream);
}
private static Byte[] StringToUTF8ByteArray(String pXmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
I am getting error + [System.OutOfMemoryException] as the file size is more than 5000 KB.
Please suggest me what should I use so that it can store and convert into the Object that I want it.
Re: StringBuilder and StreamReader
The fundemental problem is you need to close and/or dispose the stream objects when you are done using them.
If you don't and call your methods multiple times, these open stream objects will continue to hold memory and you'll get into the OOM state.
The simplest way to do ensure items get close properly is by using the 'using' block.
For example:
Code:
using( var ms = new MemoryStream( ) )
{
// use the stream here
} // ms.Dispose() automatically gets called here
However, if all you are trying to do is deserialize an xml file into class object, then there's a better way.
Code:
public static class Utility
{
public static T FromXml< T t >( string xmlFile )
{
var serializer = new XmlSerializer( typeof( T ) );
using ( var reader = XmlReader.Create( xmlFile ) )
{
return ( T ) serializer.Deserialize( reader );
}
}
}
Usage:
Code:
var myClass = Utility.FromXml< MyClass >( "myclass.xml" );
Xml Serialization in .Net truly is the best thing since sliced bread. :thumb:
Re: StringBuilder and StreamReader
I get an error on data.Append(st.ReadLine());
Re: StringBuilder and StreamReader
Well, read the error message and think about it.
Re: StringBuilder and StreamReader
String Builder doesn't have storage capacity for big files.. so what should I use instad of StringBuilder ?
Re: StringBuilder and StreamReader
That doesn't make much sense. StringBuilder is limited only by how much system memory your application is allowed to allocate. You still have not told us what the error is either. Why use a stream if you are going to load the whole thing into memory at once anyway? Doesn't make sense.