8.1. 将一个对象序列化成字符串:serializeObjToStr


// serialize an object to string
public bool serializeObjToStr(Object obj, out string serializedStr)
{
    bool serializeOk = false;
    serializedStr = "";
    try
    {
        MemoryStream memoryStream = new MemoryStream();
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(memoryStream, obj);
        serializedStr = System.Convert.ToBase64String(memoryStream.ToArray());

        serializeOk = true;
    }
    catch
    {
        serializeOk = false;
    }

    return serializeOk;
}

    

例 8.1. serializeObjToStr 的使用范例


        [Serializable]
        public struct loginInfo_t
        {
            public bool valid;
            public string username;
            public string cid;
            public string appid;
            public string bitProtocol;
            public string canary;
            public CookieCollection cookies;
            public DateTime createdTime;    // record the login info(cookie) create time
            public DateTime lastUpldateTime;// last update the login info(cookie)'s time
        };

        private bool updateLoginInfo(skydrive.loginInfo_t loginInfo)
        {
            bool updateOk = false;

            string serializedStr = "";

            loginInfo.lastUpldateTime = DateTime.Now;

            if (skydrive.commLib.serializeObjToStr(loginInfo, out serializedStr))
            {
                Settings.Default.loginInfoStr = serializedStr;
                Settings.Default.Save();

                updateOk = true;
            }