Skip to main content
 首页 » 编程设计

c#之对象到字节数组到字符串并返回

2024年02月06日25jirigala

我有一个特定的要求,将对象转换为字节数组,然后再转换为字符串。然后我需要从字符串恢复为字节数组,然后再恢复为对象。

除了最后一步,我能完成每一步。我不断收到以下异常。 “对象必须实现 IConvertible。”

对象在数据上其实是非常小的。

这里是使用的代码:

private Object ToSafeObjectFromString(String SafeString,Type ObjectType) 
{ 
    //This line throws the exception 
    byte[] BufferArray = Convert.FromBase64String(SafeString); 
    return Convert.ChangeType(CustomByteArrayToObject(BufferArray), ObjectType); 
} 
 
public static object CustomByteArrayToObject(byte[] arrBytes) 
{ 
    MemoryStream memStream = new MemoryStream(); 
    BinaryFormatter binForm = new BinaryFormatter(); 
    memStream.Write(arrBytes, 0, arrBytes.Length); 
    memStream.Seek(0, SeekOrigin.Begin); 
    object obj = (object)binForm.Deserialize(memStream); 
    return obj; 
} 
private String ToSafeStringFromObject(Object Object) 
{ 
    byte[] ByteArray = ObjectToByteArray(Object); 
    String ReturnValue = Convert.ToBase64String(ByteArray); 
    return ReturnValue; 
} 

请您参考如下方法:

您使用 ASCII 编码进行序列化,但使用 UTF-8 编码进行反序列化,这看起来是不对称的。

不要对二进制序列化使用文本编码,这有未定义的行为:您使用的二进制数组根本没有编码,它是二进制数据。

按照评论中的建议,使用 Convert.ToBase64 :

Converts an array of 8-bit unsigned integers to its equivalent string representation that is encoded with base-64 digits.

及其倒数Convert.FromBase64 :

Converts the specified string, which encodes binary data as base-64 digits, to an equivalent 8-bit unsigned integer array.