using System.IO;
using System.Text;
namespace Cryville.Common {
///
/// Provides a set of methods related to file system and IO.
///
public static class IOExtensions {
///
/// Gets a subdirectory of a directory. The subdirectory is created if it does not exist.
///
/// The parent directory.
/// The name of the subdirectory.
///
public static DirectoryInfo GetSubdirectory(this DirectoryInfo dir, string name) {
var l1 = dir.GetDirectories(name);
if (l1.Length == 0) return dir.CreateSubdirectory(name);
else return l1[0];
}
///
/// Reads a string length-prefixed with a .
///
/// The binary reader.
/// The encoding of the string.
/// The string read from the reader.
public static string ReadUInt16String(this BinaryReader reader, Encoding encoding = null) {
encoding ??= Encoding.UTF8;
var len = reader.ReadUInt16();
byte[] buffer = reader.ReadBytes(len);
return encoding.GetString(buffer);
}
///
/// Writes a string length-prefixed with a .
///
/// The binary writer.
/// The string to write by the writer.
/// The encoding of the string.
public static void WriteUInt16String(this BinaryWriter writer, string value, Encoding encoding = null) {
encoding ??= Encoding.UTF8;
byte[] buffer = encoding.GetBytes(value);
writer.Write((ushort)buffer.Length);
writer.Write(buffer);
}
}
}