TradeMe.Api.Client.PhotoMethods.UploadPhotoFormat C# (CSharp) Method

UploadPhotoFormat() public method

Performs the Photo Method: Upload a photo.

Serializes the given PhotoUploadRequest into xml and sends the message. Loads the file and converts it to the appropriate data format for the request - it does not require the "PhotoData" field of the PhotoUploadRequest object to have anything in it.

public UploadPhotoFormat ( PhotoUploadRequest up ) : System.Xml.Linq.XDocument
up PhotoUploadRequest The object that will be serialized into xml and then sent in a POST message.
return System.Xml.Linq.XDocument
        public XDocument UploadPhotoFormat(PhotoUploadRequest up)
        {
            var fileName = up.FileName;

            var fs = File.OpenRead(fileName);
            var data = new byte[fs.Length];

            // read in the file to a byte array
            using (Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                var offset = 0;
                var remaining = data.Length;
                while (remaining > 0)
                {
                    var read = stream.Read(data, offset, remaining);
                    if (read <= 0)
                    {
                        throw new EndOfStreamException(String.Format(Constants.Culture, "End of stream reached with {0} bytes left to read", remaining));
                    }

                    remaining -= read;
                    offset += read;
                }
            }

            // The data in the request is a base64 encoded string of the binary data in the photo.
            var endData = Convert.ToBase64String(data);

            // put the data in the object that will be converted to xml and posted
            up.PhotoData = endData;

            // send the post method
            return _connection.Post(up, "Photos.xml");
        }