I have a program that converts a byte[] to a string of hex:
byte[] bytes = File.ReadAllBytes(infile);
try
{
StringBuilder sb = new StringBuilder(BitConverter.ToString(bytes)); // <--exception
hexfield.Text = sb.ToString();
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
This works fine for most case. But when I use a huge file, for example a 103 MB .flv video file it runs out of memory it throws an exception:
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.String.CtorCharArrayStartLength(Char[] value, Int32 startIndex, Int32 length)
at System.BitConverter.ToString(Byte[] value, Int32 startIndex, Int32 length)
at System.BitConverter.ToString(Byte[] value)
at shex.shexx.hexfield_Dragrop(Object sender, DragEventArgs e)**
The
BitConverter.ToStringmethod first creates achararray, then creates a string from that, so you would need room for the string twice in memory.You can convert the data in smaller chunks, and create the
StringBuilderwith an initial size so that it has all the room it needs. This way the large string exists only once in memory:However, note the comment from sehe about the usefulness of such a huge string. The best solution might actually be to not create the entire string at all.