Over a million developers have joined DZone.

Get any object size in kb

·
public static int GetObjSize(Object obj)
        {
            try
            {
                string XmlString = string.Empty;
                MemoryStream MemStream = new MemoryStream();
                XmlSerializer Serializer = new XmlSerializer(obj.GetType());
                XmlTextWriter XmlText = new XmlTextWriter(MemStream, Encoding.Default);
                Serializer.Serialize(XmlText, obj);
                byte[] bytes = new byte[] { };
                bytes = MemStream.ToArray();
                XmlString = Encoding.Default.GetString(bytes, 0, bytes.Length);
                MemStream.Flush();
                MemStream.Close();
                XmlText.Flush();
                XmlText.Close();

                byte[] bytesobj = new byte[XmlString.Length * sizeof(char)];
                Buffer.BlockCopy(XmlString.ToCharArray(), 0, bytes, 0, bytes.Length);
                return bytesobj.Length;
            }
            catch (Exception e)
            {
                return -1;
            }
        }
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}