Skip to content

Writing

Eric Freed edited this page Aug 25, 2021 · 2 revisions

TagWriter

The TagWriter class is the heart and soul of writing data to a stream. It only requires a base Stream object flag indicating the data type, and with optional compression flags to begin writing,

using Stream stream = File.OpenWrite("/path/to/file.nbt");
using TagWriter writer = new TagWriter(stream, FormatOptions.BigEndian);

Once created, you are ready to start writing. For the majority of users, there is only one method that is pertinent: WriteTag and its asynchronous counterpart WriteTagAsync. There are numerous other methods available for writing each individual type of tag, though there is little reason for these to be required by consumers, as the WriteTag method will automatically select the appropriate internal write function.

Compression

Compression is not handled by the TagWriter class, it is the responsibility of higher-level abstractions to pass in the proper compression stream during initialization.

File

The static NbtFile class provides various methods for simplifying writing NBT to a file as a single invocation.

NbtFile.Write("/path/to/file1.nbt", FormatOptions.Java, CompressionType.GZip);
NbtFile.Write("/path/to/file2.nbt", FormatOptions.BedrockFile, CompressionType.ZLib, CompressionLevel.Optimal);

As with other relevant methods in SharpNBT, there is an asynchronous counterpart:

await NbtFile.WriteAsync("/path/to/file1.nbt", FormatOptions.Java, CompressionType.None);
await NbtFile.WriteAsync("/path/to/file2.nbt", FormatOptions.BedrockFile, CompressionType.GZip, CompressionLevel.Fastest);

That's all there is to it, essentially the analog of the File.WriteAllText function found in the System.IO namespace, but for NBT data instead of text. If you wish to retrieve the data as a TagWriter instance, but not consume the stream, the OpenWrite function is also available:

using TagWriter writer = NbtFile.OpenWrite("/path/to/file.nbt", FormatOptions.LittleEndian); 
Clone this wiki locally