本文实例为大家分享了针对Mongodb3.3数据库中GridFS增删改查,供大家参考,具体内容如下
Program.cs代码如下:
internal class Program { private static void Main(string[] args) { GridFSHelper helper = new GridFSHelper("mongodb://localhost", "GridFSDemo", "Pictures"); #region 上传图片 //第一种 //Image image = Image.FromFile("D:\\dog.jpg"); //byte[] imgdata = ImageHelper.ImageToBytes(image); //ObjectId oid = helper.UploadGridFSFromBytes(imgdata); //第二种 //Image image = Image.FromFile("D:\\man.jpg"); //Stream imgSteam = ImageHelper.ImageToStream(image); //ObjectId oid = helper.UploadGridFSFromStream("man",imgSteam); //LogHelper.WriteFile(oid.ToString()); // Console.Write(oid.ToString()); #endregion #region 下载图片 //第一种 //ObjectId downId = new ObjectId("578e2d17d22aed1850c7855d"); //byte[] Downdata= helper.DownloadAsByteArray(downId); //string name= ImageHelper.CreateImageFromBytes("coolcar",Downdata); //第二种 // byte[] Downdata = helper.DownloadAsBytesByName("QQQ"); //string name = ImageHelper.CreateImageFromBytes("dog", Downdata); //第三种 //byte[] Downdata = helper.DownloadAsBytesByName("QQQ"); //Image img = ImageHelper.BytesToImage(Downdata); //string path = Path.GetFullPath(@"../../DownLoadImg/") + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg"; ////使用path获取当前应用程序集的执行目录的上级的上级目录 //img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg); #endregion #region 查找图片 GridFSFileInfo gridFsFileInfo = helper.FindFiles("man"); Console.WriteLine(gridFsFileInfo.Id); #endregion #region 删除图片 //helper.DroppGridFSBucket(); #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); } //this.collection = new MongoClient(url).GetDatabase(db).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, // 1MB 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); } //The “fs.files” collection will be dropped first, followed by the “fs.chunks” collection. This is the fastest way to delete all files stored in a GridFS bucket at once. 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 { /// <summary> /// //将Image转换成流数据,并保存为byte[] /// </summary> /// <param name="image"></param> /// <returns></returns> 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]; //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin 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; } /// <summary> /// Convert Byte[] to Image /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static Image BytesToImage(byte[] buffer) { MemoryStream ms = new MemoryStream(buffer); Image image = System.Drawing.Image.FromStream(ms); return image; } /// <summary> /// Convert Byte[] to a picture and Store it in file /// </summary> /// <param name="fileName"></param> /// <param name="buffer"></param> /// <returns></returns> 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\")); //在当前程序集目录中添加指定目录DownLoadImg System.IO.Directory.CreateDirectory(info.FullName); File.WriteAllBytes(info+file, buffer); return file; } } }
LogHelper.cs代码如下:
/// <summary> /// 手动记录错误日志,不用Log4Net组件 /// </summary> public class LogHelper { /// <summary> /// 将日志写入指定的文件 /// </summary> /// <param name="Path">文件路径,如果没有该文件,刚创建</param> /// <param name="content">日志内容</param> 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(); } /// <summary> /// 将日志写入指定的文件 /// </summary> /// <param name="Path">文件路径,如果没有该文件,刚创建</param> /// <param name="content">日志内容</param> 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(); } /// <summary> /// 将日志写入指定的文件 /// </summary> /// <param name="erroMsg">错误详细信息</param> /// <param name="source">源位置</param> /// <param name="fileName">文件名</param> 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数据:
查找图片:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无争山庄资源网 Copyright www.whwtcm.com
暂无“MongoDB.NET 2.2.4驱动版本对Mongodb3.3数据库中GridFS增删改查”评论...
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新日志
2024年12月22日
2024年12月22日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]