使用MongoDB.NET 2.2.4驱动版本对 Mongodb3.3数据库中GridFS增删改查
时间:
2017-10-20 13:11:08
阅读:
314
评论:
收藏:
0
[点我收藏+]
Program.cs代码如下:
- internal class Program
- {
- private static void Main(string[] args)
- {
- GridFSHelper helper = new GridFSHelper("mongodb://localhost", "GridFSDemo", "Pictures");
-
- #region 上传图片
-
-
-
-
-
-
-
-
-
-
-
-
-
- #endregion
-
- #region 下载图片
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- #endregion
-
- #region 查找图片
- GridFSFileInfo gridFsFileInfo = helper.FindFiles("man");
- Console.WriteLine(gridFsFileInfo.Id);
- #endregion
-
- #region 删除图片
-
- #endregion
-
- Console.ReadKey();
- }
- }
GridFSHelper.cs的代码如下:
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using MongoDB.Bson;
- using MongoDB.Driver;
- using MongoDB.Driver.GridFS;
-
- namespace MongoDemo
- {
- public class GridFSHelper
- {
- private readonly IMongoClient client;
- private readonly IMongoDatabase database;
- private readonly IMongoCollection<BsonDocument> collection;
- private readonly GridFSBucket bucket;
- private GridFSFileInfo fileInfo;
- private ObjectId oid;
-
- public GridFSHelper()
- : this(
- ConfigurationManager.AppSettings["mongoQueueUrl"], ConfigurationManager.AppSettings["mongoQueueDb"],
- ConfigurationManager.AppSettings["mongoQueueCollection"])
- {
- }
-
- public GridFSHelper(string url, string db, string collectionName)
- {
- if (url == null)
- {
- throw new ArgumentNullException("url");
- }
- else
- {
- client = new MongoClient(url);
- }
-
- if (db == null)
- {
- throw new ArgumentNullException("db");
- }
- else
- {
- database = client.GetDatabase(db);
- }
-
- if (collectionName == null)
- {
- throw new ArgumentNullException("collectionName");
- }
- else
- {
- collection = database.GetCollection<BsonDocument>(collectionName);
- }
-
-
-
- GridFSBucketOptions gfbOptions = new GridFSBucketOptions()
- {
- BucketName = "bird",
- ChunkSizeBytes = 1*1024*1024,
- ReadConcern = null,
- ReadPreference = null,
- WriteConcern = null
- };
- var bucket = new GridFSBucket(database, new GridFSBucketOptions
- {
- BucketName = "videos",
- ChunkSizeBytes = 1048576,
- WriteConcern = WriteConcern.WMajority,
- ReadPreference = ReadPreference.Secondary
- });
- this.bucket = new GridFSBucket(database, null);
- }
-
- public GridFSHelper(IMongoCollection<BsonDocument> collection)
- {
- if (collection == null)
- {
- throw new ArgumentNullException("collection");
- }
- this.collection = collection;
- this.bucket = new GridFSBucket(collection.Database);
- }
-
-
- public ObjectId UploadGridFSFromBytes(string filename, Byte[] source)
- {
- oid = bucket.UploadFromBytes(filename, source);
- return oid;
- }
-
- public ObjectId UploadGridFSFromStream(string filename,Stream source)
- {
- using (source)
- {
- oid = bucket.UploadFromStream(filename, source);
- return oid;
- }
- }
-
- public Byte[] DownloadAsByteArray(ObjectId id)
- {
- Byte[] bytes = bucket.DownloadAsBytes(id);
- return bytes;
- }
-
- public Stream DownloadToStream(ObjectId id)
- {
- Stream destination = new MemoryStream();
- bucket.DownloadToStream(id, destination);
- return destination;
- }
-
- public Byte[] DownloadAsBytesByName(string filename)
- {
- Byte[] bytes = bucket.DownloadAsBytesByName(filename);
- return bytes;
- }
-
- public Stream DownloadToStreamByName(string filename)
- {
- Stream destination = new MemoryStream();
- bucket.DownloadToStreamByName(filename, destination);
- return destination;
- }
-
- public GridFSFileInfo FindFiles(string filename)
- {
- var filter = Builders<GridFSFileInfo>.Filter.And(
- Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, "man"),
- Builders<GridFSFileInfo>.Filter.Gte(x => x.UploadDateTime, new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc)),
- Builders<GridFSFileInfo>.Filter.Lt(x => x.UploadDateTime, new DateTime(2017, 2, 1, 0, 0, 0, DateTimeKind.Utc)));
- var sort = Builders<GridFSFileInfo>.Sort.Descending(x => x.UploadDateTime);
- var options = new GridFSFindOptions
- {
- Limit = 1,
- Sort = sort
- };
- using (var cursor = bucket.Find(filter, options))
- {
- fileInfo = cursor.ToList().FirstOrDefault();
- }
- return fileInfo;
- }
-
-
- public void DeleteAndRename(ObjectId id)
- {
- bucket.Delete(id);
- }
-
-
- public void DroppGridFSBucket()
- {
- bucket.Drop();
- }
-
- public void RenameAsingleFile(ObjectId id,string newFilename)
- {
- bucket.Rename(id, newFilename);
- }
-
- public void RenameAllRevisionsOfAfile(string oldFilename,string newFilename)
- {
- var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, oldFilename);
- var filesCursor = bucket.Find(filter);
- var files = filesCursor.ToList();
- foreach (var file in files)
- {
- bucket.Rename(file.Id, newFilename);
- }
- }
-
- }
- }
ImageHelper.cs的代码如下:
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Drawing.Imaging;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace MongoDemo
- {
- public static class ImageHelper
- {
-
-
-
-
-
- public static byte[] ImageToBytes(Image image)
- {
- ImageFormat format = image.RawFormat;
- using (MemoryStream ms = new MemoryStream())
- {
- if (format.Equals(ImageFormat.Jpeg))
- {
- image.Save(ms, ImageFormat.Jpeg);
- }
- else if (format.Equals(ImageFormat.Png))
- {
- image.Save(ms, ImageFormat.Png);
- }
- else if (format.Equals(ImageFormat.Bmp))
- {
- image.Save(ms, ImageFormat.Bmp);
- }
- else if (format.Equals(ImageFormat.Gif))
- {
- image.Save(ms, ImageFormat.Gif);
- }
- else if (format.Equals(ImageFormat.Icon))
- {
- image.Save(ms, ImageFormat.Icon);
- }
- byte[] buffer = new byte[ms.Length];
-
- ms.Seek(0, SeekOrigin.Begin);
- ms.Read(buffer, 0, buffer.Length);
- return buffer;
- }
- }
-
-
- public static Stream ImageToStream(Image image)
- {
- ImageFormat format = image.RawFormat;
- MemoryStream ms = new MemoryStream();
-
- if (format.Equals(ImageFormat.Jpeg))
- {
- image.Save(ms, ImageFormat.Jpeg);
- }
- else if (format.Equals(ImageFormat.Png))
- {
- image.Save(ms, ImageFormat.Png);
- }
- else if (format.Equals(ImageFormat.Bmp))
- {
- image.Save(ms, ImageFormat.Bmp);
- }
- else if (format.Equals(ImageFormat.Gif))
- {
- image.Save(ms, ImageFormat.Gif);
- }
- else if (format.Equals(ImageFormat.Icon))
- {
- image.Save(ms, ImageFormat.Icon);
- }
- return ms;
- }
-
-
- public static byte[] GetPictureData(string imagePath)
- {
- FileStream fs = new FileStream(imagePath, FileMode.Open);
- byte[] byteData = new byte[fs.Length];
- fs.Read(byteData, 0, byteData.Length);
- fs.Close();
- return byteData;
- }
-
-
-
-
-
-
-
-
- public static Image BytesToImage(byte[] buffer)
- {
- MemoryStream ms = new MemoryStream(buffer);
- Image image = System.Drawing.Image.FromStream(ms);
- return image;
- }
-
-
-
-
-
-
-
- public static string CreateImageFromBytes(string fileName, byte[] buffer)
- {
- string file = fileName;
- Image image = BytesToImage(buffer);
- ImageFormat format = image.RawFormat;
- if (format.Equals(ImageFormat.Jpeg))
- {
- file += ".jpg";
- }
- else if (format.Equals(ImageFormat.Png))
- {
- file += ".png";
- }
- else if (format.Equals(ImageFormat.Bmp))
- {
- file += ".bmp";
- }
- else if (format.Equals(ImageFormat.Gif))
- {
- file += ".gif";
- }
- else if (format.Equals(ImageFormat.Icon))
- {
- file += ".icon";
- }
- System.IO.FileInfo info = new System.IO.FileInfo(Path.GetFullPath(@"DownLoadImg\"));
- System.IO.Directory.CreateDirectory(info.FullName);
- File.WriteAllBytes(info+file, buffer);
- return file;
- }
- }
- }
LogHelper.cs代码如下:
-
-
- public class LogHelper
- {
-
-
-
-
-
- public static void WriteFile(string content)
- {
- string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";
- if (!Directory.Exists(Path))
- {
-
- Directory.CreateDirectory(Path);
- }
- Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";
- if (!File.Exists(Path))
- {
- File.Create(Path).Close();
- }
- StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));
- writer.WriteLine("时间:" + DateTime.Now.ToString());
- writer.WriteLine("日志信息:" + content);
- writer.WriteLine("-----------------------------------------------------------");
- writer.Close();
- writer.Dispose();
- }
-
-
-
-
-
-
- public static void WriteFile(int content)
- {
- string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";
- if (!Directory.Exists(Path))
- {
-
- Directory.CreateDirectory(Path);
- }
- Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";
- if (!File.Exists(Path))
- {
- File.Create(Path).Close();
- }
- StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));
- writer.WriteLine("时间:" + DateTime.Now.ToString());
- writer.WriteLine("日志信息:" + content);
- writer.WriteLine("-----------------------------------------------------------");
- writer.Close();
- writer.Dispose();
- }
-
-
-
-
-
-
-
-
- public static void WriteFile(string erroMsg, string source, string stackTrace, string fileName)
- {
- string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";
- if (!Directory.Exists(Path))
- {
-
- Directory.CreateDirectory(Path);
- }
- Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";
- if (!File.Exists(Path))
- {
- File.Create(Path).Close();
- }
- StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));
- writer.WriteLine("时间:" + DateTime.Now.ToString());
- writer.WriteLine("文件:" + fileName);
- writer.WriteLine("源:" + source);
- writer.WriteLine("错误信息:" + erroMsg);
- writer.WriteLine("-----------------------------------------------------------");
- writer.Close();
- writer.Dispose();
- }
- }
结果如下:


Mongodb数据:
查找图片:
使用MongoDB.NET 2.2.4驱动版本对 Mongodb3.3数据库中GridFS增删改查
原文:http://www.cnblogs.com/zxtceq/p/7698555.html