OdeToCode IC Logo

Using GridFS in MongoDb from C#

Tuesday, April 16, 2013

GridFS is a specification for storing large files in MongoDB. GridFS will chunk a file into documents, and the official C# driver supports GridFS.

The following class wraps some of the driver classes (MongoDatabase and MongoGridFS):

public class MongoGridFs
    private readonly MongoDatabase _db;
    private readonly MongoGridFS _gridFs;

    public MongoGridFs(MongoDatabase db)
        _db = db;
        _gridFs = _db.GridFS;

    public ObjectId AddFile(Stream fileStream, string fileName)
        var fileInfo = _gridFs.Upload(fileStream, fileName);
        return (ObjectId)fileInfo.Id;

    public Stream GetFile(ObjectId id)
        var file = _gridFs.FindOneById(id);
        return file.OpenRead();           

The following code uses the above class to put a file into MongoDB, then read it back out.

var fileName = "clip_image071.jpg";

var client = new MongoClient();
var server = client.GetServer();
var database = server.GetDatabase("testdb");
var gridFs = new MongoGridFs(database);

var id = ObjectId.Empty;            
using(var file = File.OpenRead(fileName))
    id = gridFs.AddFile(file, fileName);

using(var file = gridFs.GetFile(id))
    var buffer = new byte[file.Length];
    // note - you'll probably want to read in
    // small blocks or stream to avoid 
    // allocating large byte arrays like this
    file.Read(buffer, 0, (int)file.Length);

Gravatar Tim Jones Tuesday, April 16, 2013
An (admittedly own-horn-tooting) alternative: my Ormongo library (an ActiveRecord-style wrapper for the MongoDB C# library) has an Attachment class, which makes it quite simple to attach GridFS files to your domain models. https://github.com/tgjones/ormongo/blob/master/src/Ormongo.Tests/AttachmentTests.cs
Gravatar scott Tuesday, April 16, 2013
@Tim - nice!
Comments are closed.