c#二进制序列化输出大小

本文关键字:输出 序列化 二进制 | 更新日期: 2023-09-27 18:07:07

BinarySerializer的输出字符串似乎太长了。即使我将类的属性名缩短为单个字符长度,它也不会改变。

下面是类文件:

using System;
namespace Models.Accounts
{
    /// <summary>
    /// PasswordResetRequest class
    /// model of a password reset request
    /// </summary>
    [Serializable]
    public class PRR
    {
        /// <summary>
        /// request id
        /// </summary>
        public string I { get; set; }
        /// <summary>
        /// time request received
        /// </summary>
        public DateTime T { get; set; }
        /// <summary>
        /// application to which the password belongs
        /// </summary>
        public string A { get; set; }
        /// <summary>
        /// username whose password needs to be reset
        /// </summary>
        public string U { get; set; }
        /// <summary>
        /// token (guid)
        /// </summary>
        public Guid G { get; set; }
        /// <summary>
        /// token used
        /// </summary>
        public bool D { get; set; }
        /// <summary>
        /// client ip
        /// </summary>
        public string C { get; set; }
    }
}

,我使用这个SO链接进行序列化。当我使用序列化器

        PRR request = new PRR();
        request.U = "someusername";
        request.G = Guid.NewGuid();
        string searlizedRequest = SingletonCommon.Instance.SerializeObject(request);

我得到searlizedRequest的一个很长的值,比如AAEAAAD/////AQAAAAAAAAAMAgAAAEFMSVQuTW9kZWxzLCBWZXJzaW9uPTEuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49bnVsbAUBAAAAF0xJVC5Nb2RlbHMuQWNjb3VudHMuUFJSBwAAABI8ST5rX19CYWNraW5nRmllbGQSPFQ+a19fQmFja2luZ0ZpZWxkEjxBPmtfX0JhY2tpbmdGaWVsZBI8VT5rX19CYWNraW5nRmllbGQSPEc+a19fQmFja2luZ0ZpZWxkEjxEPmtfX0JhY2tpbmdGaWVsZBI8Qz5rX19CYWNraW5nRmllbGQBAAEBAwABDQtTeXN0ZW0uR3VpZAECAAAACgAAAAAAAAAACgYDAAAADHNvbWV1c2VybmFtZQT8////C1N5c3RlbS5HdWlkCwAAAAJfYQJfYgJfYwJfZAJfZQJfZgJfZwJfaAJfaQJfagJfawAAAAAAAAAAAAAACAcHAgICAgICAgL20za6r7D0QbKWb7tG1cjSAAoL

是否有任何格式器与较短的输出,我可以使用或其他任何我可以尝试,因为这个字符串将是在电子邮件中发送的链接的一部分。

c#二进制序列化输出大小

也许你可以尝试GZipStream压缩输出时写入一个文件有最小的大小

public static void SetCompressed<T>(T data,string name) 
{
    BinaryFormatter bf;
    using(FileStream fileStream = new FileStream(name+ ".object", FileMode.Create, FileAccess.Write))
    using(GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Compress))
    {
        bf.Serialize(compressionStream, data);
    }
}
public static T GetCompressed<T>(string name) 
{
    BinaryFormatter bf;
    T Tobject;
    using(FileStream fileStream = new FileStream(name + ".object", FileMode.Open, FileAccess.Read))
    using(GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Decompress))
    {
        Tobject = (T)bf.Deserialize(compressionStream);
    }
    return Tobject;
}

上面的代码使用BinaryFormatterFileStream &GZipStreamGZipStream将压缩输出*。object file .

HACK:你可以打开*。object文件与7-Zip查看序列化的内容。