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);
Read more: Ode to code
QR:
0 comments:
Post a Comment