Proper Memory Serialization Usage

I was having trouble at the start but managed to get scripted files uploading to Dropbox, but it takes so many steps I was hoping someone more experienced can confirm if Im taking the right approach or if there is a simpler way.

Im taking a serialized script, and phrasing it data stream to the UploadAsync() command to be put onto Dropbox.

Also, with the using() eclosed statement on a MemoryStream, do I have to call MemoryStream.Close() at the end? Or does it close itself when the using() statemnt ends?

public async void ResyncCatalogueDatabaseAsync()
    {
        using (var dbx = new DropboxClient(XXXXXXXXXXX)))
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            using (MemoryStream memoryStream = new MemoryStream())
            {
                binaryFormatter.Serialize(memoryStream, catalogueDatabase);
                using (MemoryStream uploadStream =
                new MemoryStream(memoryStream.ToArray()))
                {
                    await dbx.Files.UploadAsync("PATH", WriteMode, body: uploadStream);
                    Debug.Log("LOG: Catalouge Updated" + DateTime.Now.ToLongDateString());
                }
            }
        }  
    }

Thank you :slight_smile:

There’s no need to copy the first MemoryStream to another MemoryStream using the ‘ToArray’ method.

You’ve effectively made a triplicates of the MemoryStream. The first one that the serializer puts all the info into, the second that its duplicated into… and technically a giant chunk of memory to represent the array you converted the stream to.

Instead just set the first MemoryStream position back to 0, and upload that instead.

    public async void ResyncCatalogueDatabaseAsync()
    {
        using (var dbx = new DropboxClient(XXXXXXXXXXX)))
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            using (MemoryStream memoryStream = new MemoryStream())
            {
                binaryFormatter.Serialize(memoryStream, catalogueDatabase);
                memoryStream.Position = 0;
                await dbx.Files.UploadAsync("PATH", WriteMode, body: memoryStream);
                Debug.Log("LOG: Catalouge Updated" + DateTime.Now.ToLongDateString());
            }
        } 
    }

As for if this is proper… no idea, not personally familiar with the DropboxClient api you’re using.

1 Like