代码之家  ›  专栏  ›  技术社区  ›  pseudodev

是否可以在C#中序列化流的内容,然后在Python中反序列化?

  •  0
  • pseudodev  · 技术社区  · 2 年前

    这里有点奇怪。我有一个现有的函数,可以将ZIP文件写入流中。

    await WriteZipToStream(streamToWriteTo);
    

    我还有一个功能,可以将字符串上传到安全的地方。

    await SaveStringInSecureWay(stringToSave);
    

    将ZIP作为流和我 将其保存为字符串。稍后,我将需要在一些Python代码中将字符串反序列化回ZIP文件。

    这可能吗?我正在努力找出序列化流内容的正确方法,然后可以从Python中对这些内容进行反序列化。

    2 回复  |  直到 2 年前
        1
  •  2
  •   SuperStew    2 年前

    先做一点准备

    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.
    

    然后是蟒蛇

    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)
    
        2
  •  0
  •   Ben Lin    2 年前

    听起来你在谈论可读字符串,比如base64编码。

    如果您谈论的是二进制流存储到二进制文件(将字符串上传到安全的地方),那么它本质上就是zip文件。 如果您在base64编码中收到“可读字符串”,则将其保存到文本文件中,然后在python代码中读取字符串并使用base64解码将其转换为二进制文件(zip文件)。这也很简单。