92 lines
2.9 KiB
C#
92 lines
2.9 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Threading.Tasks;
|
|
using System.Text;
|
|
using LibAC.NBT.API;
|
|
|
|
namespace LibAC.NBT.API
|
|
{
|
|
public static class SnbtIo
|
|
{
|
|
/// <summary>
|
|
/// Writes a CompoundTag to a file in SNBT format.
|
|
/// </summary>
|
|
/// <param name="file">The file path to write to.</param>
|
|
/// <param name="tag">The CompoundTag to write.</param>
|
|
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());
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reads a tag from a file in SNBT format.
|
|
/// </summary>
|
|
/// <param name="file">The file path to read from.</param>
|
|
/// <returns>A Task resolving to the read Tag.</returns>
|
|
public static async Task<Tag> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Converts a CompoundTag to its SNBT string representation.
|
|
/// </summary>
|
|
/// <param name="tag">The CompoundTag to convert.</param>
|
|
/// <returns>A string representing the CompoundTag in SNBT format.</returns>
|
|
public static string WriteToString(CompoundTag tag)
|
|
{
|
|
var builder = new StringBuilder();
|
|
Tag.WriteStringifiedNamedTag(tag, builder, 0);
|
|
return builder.ToString();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reads a Tag from an SNBT string.
|
|
/// </summary>
|
|
/// <param name="data">The SNBT string to read.</param>
|
|
/// <returns>A Task resolving to the read Tag.</returns>
|
|
public static Task<Tag> ReadFromString(string data)
|
|
{
|
|
var stringReader = new StringReader(data);
|
|
return Task.FromResult(Tag.ReadStringifiedNamedTag(stringReader));
|
|
}
|
|
}
|
|
}
|