在MonoDevelop中使用GridFS和官方C#驱动程序

时间:2015-05-10 05:03:11

标签: c# mongodb monodevelop mongodb-.net-driver freebsd

我在PC-BSD 10.1上使用MonoDevelop并使用MongoDB 3.2。我从Nuget下载了MongoDB.Driver(+ Bson& Core)。我可以进行基本的读写操作,并尝试通过遵循StackOverflow中最新的示例来使GridFS工作:

MongoDB GridFs with C#, how to store files such as images?

首先,我的系统不识别(貌似)静态MongoServer类,所以我切换到MognoClient来获取数据库。然后我得到以下内容:

"输入MongoDB.Driver.IMongoDatabase' does not contain a definition for GridFS'没有扩展方法GridFS' of type MongoDB.Driver.IMongoDatabase'可以找到。 "

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);
                    } 
                }
            }
        }
    }
}

我做了什么愚蠢的错误? GridFS是否有依赖我缺失?这应该工作! :(

Dinsdale

2 个答案:

答案 0 :(得分:13)

对于驱动程序版本2.2,您必须下载一个名为MongoDB.Driver.GridFS的单独NuGet包。

你可以这样使用它:

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);

Here the full doc

答案 1 :(得分:3)

您已下载2.0版本的驱动程序。它目前没有GridFS API。您可以在此处跟踪该功能(https://jira.mongodb.org/browse/CSHARP-1191)。此外,MongoServer已经不再使用2.0 API了。

但是,如果您提取mongocsharpdriver nuget包,则可以使用旧版API的包装器。有了它,你将同时拥有MongoServer和GridFS。