Search code examples
c#mongodbmonodevelopmongodb-.net-driverfreebsd

Using GridFS with official C# driver in MonoDevelop


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 forGridFS' and no extension method GridFS' of typeMongoDB.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


Solution

  • 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.