// MongoDB连接串,以[mongodb://]开头。这里,我们连接的是本机的服务
string connectionString = "mongodb://localhost";
// 连接到一个MongoServer上
MongoServer server = MongoServer.Create(connectionString);
// 打开数据库testdb
MongoDatabase db = server.GetDatabase("testdb");
//文件操作,支持大于4M的数据
MongoGridFS fs = new MongoGridFS(db);
//写入
using (MongoGridFSStream sw = fs.Create("tmp.xml"))
{
byte[] fileByte = File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + "MongoDB.Bson.xml");
sw.Write(fileByte, 0, fileByte.Length);
}
//读取
using (MongoGridFSStream sr = fs.OpenRead("tmp.xml"))
{
byte[] fileByte=new byte[sr.Length];
sr.Read(fileByte, 0, (int)sr.Length);
File.WriteAllBytes("tmp.xml", fileByte);
}
//删除文件
fs.Delete("tmp.xml");