Deleting and Renaming Files

These methods allow you to delete or rename GridFS files.

Deleting a single file

Use the Delete or DeleteAsync methods to delete a single file identified by its Id.

IGridFSBucket bucket;
ObjectId id;
bucket.Delete(id);
await bucket.DeleteAsync(id);

Dropping an entire GridFS bucket

Use the Drop or DropAsync methods to drop an entire GridFS bucket at once.

IGridFSBucket bucket;
bucket.Drop();
await bucket.DropAsync();

Note
The “fs.files” collection will be dropped first, followed by the “fs.chunks” collection. This is the fastest way to delete all files stored in a GridFS bucket at once.

Renaming a single file

Use the Rename or RenameAsync methods to rename a single file identified by its Id.

IGridFSBucket bucket;
ObjectId id;
string newFilename;
bucket.Rename(id, newFilename);
await bucket.RenameAsync(id, newFilename);

Renaming all revisions of a file

To rename all revisions of a file you first use the Find or FindAsync method to find all the revisions, and then loop over the revisions and use the Rename or RenameAsync method to rename each revision one at a time.

IGridFSBucket bucket;
string oldFilename;
string newFilename;
var filter = Builders<GridFSFileInfo>.Filter.EQ(x => x.Filename, oldFilename);
var filesCursor = bucket.Find(filter);
var files = filesCursor.ToList();

foreach (var file in files)
{
    bucket.Rename(file.Id, newFilename);
}
var filesCursor = await bucket.FindAsync(filter);
var files = await filesCursor.ToListAsync();

foreach (var file in files)
{
    await bucket.RenameAsync(file.Id, newFilename);
}