Search code examples
pythonc#.netserialization

Is it possible to serialize a stream's contents in C# and then deserialize it in Python?


Bit of a weird case here. I have an existing function that writes a ZIP file to a stream.

await WriteZipToStream(streamToWriteTo);

I have another function that upload a string to a secure place.

await SaveStringInSecureWay(stringToSave);

I have to get the ZIP as a stream and I have to save it as a string. I'll then later need to deserialize the string back to a ZIP file in some Python code.

Is this possible? I'm struggling to figure out the correct way to serialize the stream contents that can then be deserialized from within Python.


Solution

  • a little prep first

    MemoryStream memoryStream = new MemoryStream(); //First, convert the ZIP file stream into a byte array.
    await WriteZipToStream(memoryStream);
    byte[] zipBytes = memoryStream.ToArray();
    
    string base64ZipString = Convert.ToBase64String(zipBytes); //Convert the byte array to a Base64 encoded string
    
    await SaveStringInSecureWay(base64ZipString); //you can use your SaveStringInSecureWay method to save this Base64 encoded string.
    

    then the python

    import base64
    
    base64_zip_string = retrieve_saved_string()  # Replace with your retrieval method
    zip_bytes = base64.b64decode(base64_zip_string)
    with open('output.zip', 'wb') as zip_file:
        zip_file.write(zip_bytes)