Navigation

Compact a Realm - .NET SDK

On this page

  • Overview
  • Compaction Options
  • Realm Configuration File
  • Realm.Compact() Method

Over time, the storage space used by Realm might become fragmented and take up more space than necessary. To rearrange the internal storage and potentially reduce the file size, you can compact the Realm file.

Important
Realm file must not be in use

Realm cannot compact a file that is in use. Be sure there are no open instances that use the file.

Realm reduces the file size by writing a new (compact) version of the file, and then replacing the original with the newly-written file. Therefore, to compact, you must have free storage space equivalent to the original realm file size.

You can configure realm to automatically compact the database each time a Realm is opened, or you can compact the file without first obtaining a Realm instance.

You can configure Realm to check the Realm file each time it is opened by specifying a ShouldCompactDelegate in the configuration. The following code example shows how to do this:

config = new RealmConfiguration()
{
ShouldCompactOnLaunch = (totalBytes, usedBytes) =>
{
/* totalBytes refers to the size of the file on disk in
* bytes (data + free space).
* usedBytes refers to the number of bytes used by
* the realm file
*/
// Compact if the file is over 100MB in size or more
// than 50% 'used'
var oneHundredMB = 100 * 1024 * 1024;
return (totalBytes > (double)oneHundredMB) ||
((double)usedBytes / totalBytes > 0.5);
}
};
var realm = await Realm.GetInstanceAsync(config);

If the delegate returns true -- and the file is not in use -- the realm file is compacted prior to making the instance available.

Alternatively, you can compact a realm file without first obtaining an instance to the Realm by calling the Compact() method. The following example shows how to do this:

config = new RealmConfiguration("my.realm");
Realm.Compact(config);

The Compact method will return true if the operation is successful.

Give Feedback

On this page

  • Overview
  • Compaction Options
  • Realm Configuration File
  • Realm.Compact() Method