[英]Using GridFS with official C# driver in MonoDevelop
我在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 for
GridFS MongoDB.Driver.IMongoDatabase' does not contain a definition for
',并且找不到GridFS' of type
MongoDB.Driver.IMongoDatabase' does not contain a definition for
MongoDB.Driver.IMongoDatabase'的扩展方法GridFS' of type
。”
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.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);
这里是完整的文档 。
您已下载2.0版本的驱动程序。 它目前没有GridFS API。 您可以在此处跟踪该功能( https://jira.mongodb.org/browse/CSHARP-1191 )。 此外,MongoServer已经不再使用2.0 API了。
但是,如果您拉动mongocsharpdriver nuget包,则可以使用旧版API的包装器。 有了它,你将拥有MongoServer和GridFS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.