ForeverZer0 / SharpNBT

A pure CLS-compliant C# implementation of the Named Binary Tag (NBT) format specification commonly used with Minecraft applications, allowing easy reading/writing streams and serialization to other formats.
MIT License
25 stars 9 forks source link

Error when using SharpNBT in a little dotnet core project: Unable to cast SharpNBT.StringTag to type SharpNBT.CompoundTag #7

Open davidbitterlich opened 1 year ago

davidbitterlich commented 1 year ago

Hello,

I've just created a little console application to see whether SharpNBT suits my needs, I need a small utility to extract nbt tags from a bedrock level.dat file (and be able to edit and write back). I'm still not sure whether SharpNBT is able to read the information from that file format...

But in short, I've found the following problem: An unhandled exception of type 'System.InvalidCastException' occurred in System.Private.CoreLib.dll: 'Unable to cast object of type 'SharpNBT.StringTag' to type 'SharpNBT.CompoundTag'.'

The code which caused this unhandled exception is pretty simple:

using SharpNBT;

namespace NbtTeset 
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = "/home/david/Downloads/20220828/level.dat";
            var tag = NbtFile.Read(file, FormatOptions.BedrockFile, CompressionType.AutoDetect);
            Console.WriteLine(tag.PrettyPrinted());
        }
    }
}

The exception is thrown at the line where tag is declared and initialized with the result of NbtFile.Read(). I don't know if I am doing something wrong in here, if SharpNBT is unable to handle bedrock worlds or if there is a bug in SharpNBT - that's why I created this issue and hope you may be able to tell me what I'm doing wrong or whether it's really an issue :)

One additional info regarding the file I want to read: it's a world from Bedrock Dedicated Server..

ForeverZer0 commented 1 year ago

Your code appears to be correct, I suspect that the root cause is an error deserializing/decompressing the file. The invalid cast exception is likely just caused from attempting to read a tag type from an incorrect position in the stream. While it is still likely a bug in the library either way, does it happen to work with other Bedrock files?

I don't personally have the Bedrock version of Minecraft, and was relying upon downloading Bedrock format files from internet to do testing, therefore is may not have been as robust as it should have been with that format.

davidbitterlich commented 1 year ago

Ah okay, you may create a fresh new world using Bedrock Dedicated Server as well if you would like to analyse a living example of that format.

Bedrock Dedicated Server may be obtained for free and works on Windows as well as on Linux. I could also create a minecraft world for you and upload it somewhere where you can access it.