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

Din*_*ale 2 c# freebsd monodevelop mongodb mongodb-.net-driver

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

使用C#的MongoDB GridFs,如何存储图像等文件?

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

"类型MongoDB.Driver.IMongoDatabase' does not contain a definition forGridFS的'没有扩展方法GridFS' of typeMongoDB.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);
                    } 
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Dinsdale

dan*_*iax 13

使用2.2版驱动程序,您可以下载一个名为的单独NuGet包MongoDB.Driver.GridFS.

你可以这样使用它:

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);
Run Code Online (Sandbox Code Playgroud)

这里是完整的文档.