Reputation: 651
I am using MonoDevelop on PC-BSD 10.1 and working with MongoDB 3.2. I downloaded MongoDB.Driver (+Bson& Core) from Nuget. I can do basic reads and writes and was trying to get GridFS working by following what seems to be the most current example from StackOverflow:
MongoDB GridFs with C#, how to store files such as images?
First, my system doesn't recognize the (seemingly) static MongoServer class, so I switch to MognoClient to get a database. Then I get the following:
"Type MongoDB.Driver.IMongoDatabase' does not contain a definition for
GridFS' and no extension method GridFS' of type
MongoDB.Driver.IMongoDatabase' could be found. "
using System;
using System.IO;
using MongoDB;
using MongoDB.Driver;
using MongoDB.Driver.Core;
using MongoDB.Bson;
//using MongoDB.Driver.GridFS; -> an attempt to use the legacy driver.
namespace OIS.Objektiv.SocketServer
{
public class Gridfs
{
public Gridfs ()
{
var server = MongoServer.Create("mongodb://localhost:27017");
var database = server.GetDatabase("test");
// var client = new MongoClient("mongodb://localhost:27017");
// var database = client.GetDatabase("test");
var fileName = "D:\\Untitled.png";
var newFileName = "D:\\new_Untitled.png";
using (var fs = new FileStream(fileName, FileMode.Open))
{
var gridFsInfo = database.GridFS.Upload(fs, fileName);
var fileId = gridFsInfo.Id;
ObjectId oid= new ObjectId(fileId);
var file = database.GridFS.FindOne(Query.EQ("_id", oid));
using (var stream = file.OpenRead())
{
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
using(var newFs = new FileStream(newFileName, FileMode.Create))
{
newFs.Write(bytes, 0, bytes.Length);
}
}
}
}
}
}
What stupid error have I done? Does GridFS have a dependency I'm missing? This should work! :(
Dinsdale
Upvotes: 2
Views: 7171
Reputation: 13096
With driver version 2.2 you have do download a separate NuGet package called MongoDB.Driver.GridFS
.
You can use it this way:
IMongoDatabase database;
var bucket = new GridFSBucket(database, new GridFSOptions
{
BucketName = "videos",
ChunkSizeBytes = 1048576, // 1MB
WriteConcern = WriteConcern.Majority,
ReadPreference = ReadPeference.Secondary
});
IGridFSBucket bucket;
bytes[] source;
var options = new GridFSUploadOptions
{
ChunkSizeBytes = 64512, // 63KB
Metadata = new BsonDocument
{
{ "resolution", "1080P" },
{ "copyrighted", true }
}
};
var id = bucket.UploadFromBytes("filename", source, options);
Upvotes: 13
Reputation: 12624
You have downloaded the 2.0 version of the driver. It currently does not have a GridFS API. You can track that feature here(https://jira.mongodb.org/browse/CSHARP-1191). In addition, MongoServer is gone in the 2.0 API.
However, there is a wrapper for the legacy API available available if you pull the mongocsharpdriver nuget package. With that, you'll have both MongoServer and GridFS.
Upvotes: 3