Search code examples
c#.netdecodeencodehalcon

encode and decode strange .shm file data to and from base64 c#


first a depressing fact: https://www.base64decode.org/ can do what i want to do.

i´m trying to encode and decode (to and from base64) a model file (.shm) generated by the image processing tool MVTec Halcon because i want to store it in a xml file.

If i open it, it has this strange form:

HSTF ÿÿÿÿ¿€          Q¿ÙG®záH?Üä4©±w?­Eè}‰@?ð ................

I´m using this methods to encode and decode it:

    public static string Base64Encode(string text)
    {
        Byte[] textBytes = Encoding.Default.GetBytes(text);
        return Convert.ToBase64String(textBytes);
    }

    public static string Base64Decode(string base64EncodedData)
    {
        Byte[] base64EncodedBytes = Convert.FromBase64String(base64EncodedData);
        return Encoding.Default.GetString(base64EncodedBytes);
    }

and calling the methods from a gui like this:

    var model = File.ReadAllText(@"C:\Users\\Desktop\model_region_nut.txt");
    var base64 = ImageConverter.Base64Encode(model);
    File.WriteAllText(@"C:\Users\\Desktop\base64.txt", base64);

    var modelneu = ImageConverter.Base64Decode(File.ReadAllText(@"C:\Users\\Desktop\base64.txt"));
    File.WriteAllText(@"C:\Users\\Desktop\modelneu.txt", modelneu);

my result for modelneu is:

HSTF ??????          Q??G?z?H???4??w??E?}??@??

so you can see that there are lots of missing characters.. I guess the problem is caused by using .Default.

Thanks for your help, Michel


Solution

  • If you're working with binary data, there is no reason at all to go through text decoding and encoding. Doing so only risks corrupting the data in various ways, even if you're using a consistent character encoding.

    Just use File.ReadAllBytes() instead of File.ReadAllText() and skip the unnecessary Encoding step.