using System; using System.IO; using System.Threading.Tasks; using System.Text; using LibAC.NBT.API; namespace LibAC.NBT.API { public static class SnbtIo { /// /// Writes a CompoundTag to a file in SNBT format. /// /// The file path to write to. /// The CompoundTag to write. public static async Task WriteToFile(string file, CompoundTag tag) { var fileInfo = new FileInfo(file); if (fileInfo.Exists) { fileInfo.Delete(); // Ensure the file is reset to 0 bytes. } var builder = new StringBuilder(); Tag.WriteStringifiedNamedTag(tag, builder, 0); using (var writer = new StreamWriter(file)) { await writer.WriteAsync(builder.ToString()); } } /// /// Reads a tag from a file in SNBT format. /// /// The file path to read from. /// A Task resolving to the read Tag. public static async Task ReadFromFile(string file) { var fileInfo = new FileInfo(file); if (!fileInfo.Exists) { throw new FileNotFoundException($"File not found: {file}"); } string data; using (var reader = new StreamReader(file)) { data = await reader.ReadToEndAsync(); } var stringReader = new StringReader(data); Tag tag = new CompoundTag(); try { tag = Tag.ReadStringifiedNamedTag(stringReader); } catch (Exception ex) { Console.WriteLine($"FATAL ERROR OCCURRED AT LOCATION:\n{stringReader.GetSnapshot()}"); Console.WriteLine(ex); } return tag; } /// /// Converts a CompoundTag to its SNBT string representation. /// /// The CompoundTag to convert. /// A string representing the CompoundTag in SNBT format. public static string WriteToString(CompoundTag tag) { var builder = new StringBuilder(); Tag.WriteStringifiedNamedTag(tag, builder, 0); return builder.ToString(); } /// /// Reads a Tag from an SNBT string. /// /// The SNBT string to read. /// A Task resolving to the read Tag. public static Task ReadFromString(string data) { var stringReader = new StringReader(data); return Task.FromResult(Tag.ReadStringifiedNamedTag(stringReader)); } } }