using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace GMWare.IO { /// /// Collection of methods for reading strings using BinaryReader /// public static class StringReadingHelper { /// /// Reads a string of a given length. /// /// BinaryReader to read from /// Length of string to read /// The string that was read. public static string ReadLengthedString(BinaryReader reader, int length) { return new string(reader.ReadChars(length)); } /// /// Reads a null terminated string. /// /// BinaryReader to read from /// The string that was read. public static string ReadNullTerminatedString(BinaryReader reader) { StringBuilder sb = new StringBuilder(); for (char ch = reader.ReadChar(); ch != '\0'; ch = reader.ReadChar()) { sb.Append(ch); } return sb.ToString(); } /// /// Reads a null terminated string from within a fixed size block. /// /// BinaryReader to read from /// The length of the fixed size block /// The encoding the string is in /// The string that was read. public static string ReadNullTerminatedStringFromFixedSizeBlock(BinaryReader reader, int blockLen, Encoding encoding) { byte[] data = reader.ReadBytes(blockLen); string str = encoding.GetString(data); int indNull = str.IndexOf('\0'); if (indNull >= 0) { return str.Substring(0, indNull); } else { return str; } } } }