码迷,mamicode.com
首页 > 数据库 > 详细

使用MongoDB.NET 2.2.4驱动版本对 Mongodb3.3数据库中GridFS增删改查

时间:2017-10-20 13:42:11      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:创建   proc   article   odi   dog   ide   detail   equals   ==   

Program.cs代码如下:

 

[csharp] view plain copy
 
  1. internal class Program  
  2.     {  
  3.         private static void Main(string[] args)  
  4.         {  
  5.             GridFSHelper helper = new GridFSHelper("mongodb://localhost", "GridFSDemo", "Pictures");  
  6.  
  7.             #region 上传图片  
  8.   
  9.             //第一种  
  10.             //Image image = Image.FromFile("D:\\dog.jpg");  
  11.             //byte[] imgdata = ImageHelper.ImageToBytes(image);  
  12.             //ObjectId oid = helper.UploadGridFSFromBytes(imgdata);  
  13.   
  14.             //第二种  
  15.             //Image image = Image.FromFile("D:\\man.jpg");  
  16.             //Stream imgSteam = ImageHelper.ImageToStream(image);  
  17.             //ObjectId oid = helper.UploadGridFSFromStream("man",imgSteam);   
  18.             //LogHelper.WriteFile(oid.ToString());  
  19.             // Console.Write(oid.ToString());   
  20.  
  21.             #endregion  
  22.  
  23.             #region 下载图片  
  24.   
  25.             //第一种  
  26.             //ObjectId downId = new ObjectId("578e2d17d22aed1850c7855d");  
  27.             //byte[] Downdata=  helper.DownloadAsByteArray(downId);  
  28.             //string name=  ImageHelper.CreateImageFromBytes("coolcar",Downdata);  
  29.   
  30.             //第二种  
  31.             // byte[] Downdata = helper.DownloadAsBytesByName("QQQ");  
  32.             //string name = ImageHelper.CreateImageFromBytes("dog", Downdata);  
  33.   
  34.             //第三种  
  35.             //byte[] Downdata = helper.DownloadAsBytesByName("QQQ");  
  36.             //Image img = ImageHelper.BytesToImage(Downdata);  
  37.             //string path = Path.GetFullPath(@"../../DownLoadImg/") + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";  
  38.             ////使用path获取当前应用程序集的执行目录的上级的上级目录  
  39.             //img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);  
  40.  
  41.             #endregion  
  42.  
  43.             #region 查找图片  
  44.             GridFSFileInfo gridFsFileInfo = helper.FindFiles("man");  
  45.             Console.WriteLine(gridFsFileInfo.Id);  
  46.             #endregion  
  47.  
  48.             #region 删除图片  
  49.             //helper.DroppGridFSBucket();  
  50.             #endregion  
  51.   
  52.             Console.ReadKey();  
  53.         }  
  54.     }  

GridFSHelper.cs的代码如下:

 

 

[csharp] view plain copy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Threading.Tasks;  
  8. using MongoDB.Bson;  
  9. using MongoDB.Driver;  
  10. using MongoDB.Driver.GridFS;  
  11.   
  12. namespace MongoDemo  
  13. {  
  14.     public class GridFSHelper  
  15.     {  
  16.         private readonly IMongoClient client;  
  17.         private readonly IMongoDatabase database;  
  18.         private readonly IMongoCollection<BsonDocument> collection;  
  19.         private readonly GridFSBucket bucket;  
  20.         private GridFSFileInfo fileInfo;  
  21.         private ObjectId oid;  
  22.   
  23.         public GridFSHelper()  
  24.             : this(  
  25.                 ConfigurationManager.AppSettings["mongoQueueUrl"], ConfigurationManager.AppSettings["mongoQueueDb"],  
  26.                 ConfigurationManager.AppSettings["mongoQueueCollection"])  
  27.         {  
  28.         }  
  29.   
  30.         public GridFSHelper(string url, string db, string collectionName)  
  31.         {  
  32.             if (url == null)  
  33.             {  
  34.                 throw new ArgumentNullException("url");  
  35.             }  
  36.             else  
  37.             {  
  38.                 client = new MongoClient(url);  
  39.             }  
  40.   
  41.             if (db == null)  
  42.             {  
  43.                 throw new ArgumentNullException("db");  
  44.             }  
  45.             else  
  46.             {  
  47.                 database = client.GetDatabase(db);  
  48.             }  
  49.   
  50.             if (collectionName == null)  
  51.             {  
  52.                 throw new ArgumentNullException("collectionName");  
  53.             }  
  54.             else  
  55.             {  
  56.                 collection = database.GetCollection<BsonDocument>(collectionName);  
  57.             }  
  58.   
  59.             //this.collection = new MongoClient(url).GetDatabase(db).GetCollection<BsonDocument>(collectionName);  
  60.   
  61.             GridFSBucketOptions gfbOptions = new GridFSBucketOptions()  
  62.             {  
  63.                 BucketName = "bird",  
  64.                 ChunkSizeBytes = 1*1024*1024,  
  65.                 ReadConcern = null,  
  66.                 ReadPreference = null,  
  67.                 WriteConcern = null  
  68.             };  
  69.             var bucket = new GridFSBucket(database, new GridFSBucketOptions  
  70.             {  
  71.                 BucketName = "videos",  
  72.                 ChunkSizeBytes = 1048576, // 1MB  
  73.                 WriteConcern = WriteConcern.WMajority,  
  74.                 ReadPreference = ReadPreference.Secondary  
  75.             });  
  76.             this.bucket = new GridFSBucket(database, null);  
  77.         }  
  78.   
  79.         public GridFSHelper(IMongoCollection<BsonDocument> collection)  
  80.         {  
  81.             if (collection == null)  
  82.             {  
  83.                 throw new ArgumentNullException("collection");  
  84.             }  
  85.             this.collection = collection;  
  86.             this.bucket = new GridFSBucket(collection.Database);  
  87.         }  
  88.   
  89.   
  90.         public ObjectId UploadGridFSFromBytes(string filename, Byte[] source)  
  91.         {  
  92.             oid = bucket.UploadFromBytes(filename, source);  
  93.             return oid;  
  94.         }  
  95.   
  96.         public ObjectId UploadGridFSFromStream(string filename,Stream source)  
  97.         {  
  98.             using (source)  
  99.             {  
  100.                 oid = bucket.UploadFromStream(filename, source);  
  101.                 return oid;  
  102.             }  
  103.         }  
  104.   
  105.         public Byte[] DownloadAsByteArray(ObjectId id)  
  106.         {  
  107.             Byte[] bytes = bucket.DownloadAsBytes(id);  
  108.             return bytes;  
  109.         }  
  110.   
  111.         public Stream DownloadToStream(ObjectId id)  
  112.         {  
  113.             Stream destination = new MemoryStream();  
  114.             bucket.DownloadToStream(id, destination);  
  115.             return destination;  
  116.         }  
  117.   
  118.         public Byte[] DownloadAsBytesByName(string filename)  
  119.         {  
  120.             Byte[] bytes = bucket.DownloadAsBytesByName(filename);  
  121.             return bytes;  
  122.         }  
  123.   
  124.         public Stream DownloadToStreamByName(string filename)  
  125.         {  
  126.             Stream destination = new MemoryStream();  
  127.             bucket.DownloadToStreamByName(filename, destination);  
  128.             return destination;  
  129.         }  
  130.   
  131.         public GridFSFileInfo FindFiles(string filename)  
  132.         {  
  133.             var filter = Builders<GridFSFileInfo>.Filter.And(  
  134.             Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, "man"),  
  135.             Builders<GridFSFileInfo>.Filter.Gte(x => x.UploadDateTime, new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc)),  
  136.             Builders<GridFSFileInfo>.Filter.Lt(x => x.UploadDateTime, new DateTime(2017, 2, 1, 0, 0, 0, DateTimeKind.Utc)));  
  137.             var sort = Builders<GridFSFileInfo>.Sort.Descending(x => x.UploadDateTime);  
  138.             var options = new GridFSFindOptions  
  139.             {  
  140.                 Limit = 1,  
  141.                 Sort = sort  
  142.             };  
  143.             using (var cursor = bucket.Find(filter, options))  
  144.             {  
  145.                  fileInfo = cursor.ToList().FirstOrDefault();  
  146.             }  
  147.             return fileInfo;  
  148.         }  
  149.   
  150.   
  151.         public void DeleteAndRename(ObjectId id)  
  152.         {  
  153.             bucket.Delete(id);  
  154.         }  
  155.   
  156.         //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.   
  157.         public void DroppGridFSBucket()  
  158.         {  
  159.             bucket.Drop();  
  160.         }  
  161.   
  162.         public void RenameAsingleFile(ObjectId id,string newFilename)  
  163.         {  
  164.             bucket.Rename(id, newFilename);  
  165.         }  
  166.   
  167.         public void RenameAllRevisionsOfAfile(string oldFilename,string newFilename)  
  168.         {  
  169.             var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename, oldFilename);  
  170.             var filesCursor = bucket.Find(filter);  
  171.             var files = filesCursor.ToList();  
  172.             foreach (var file in files)  
  173.             {  
  174.                 bucket.Rename(file.Id, newFilename);  
  175.             }  
  176.         }  
  177.   
  178.     }  
  179. }  

ImageHelper.cs的代码如下:

 

 

[csharp] view plain copy
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Drawing.Imaging;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace MongoDemo  
  11. {  
  12.     public static class ImageHelper  
  13.     {  
  14.         /// <summary>  
  15.         /// //将Image转换成流数据,并保存为byte[]     
  16.         /// </summary>  
  17.         /// <param name="image"></param>  
  18.         /// <returns></returns>  
  19.         public static byte[] ImageToBytes(Image image)  
  20.         {  
  21.             ImageFormat format = image.RawFormat;  
  22.             using (MemoryStream ms = new MemoryStream())  
  23.             {  
  24.                 if (format.Equals(ImageFormat.Jpeg))  
  25.                 {  
  26.                     image.Save(ms, ImageFormat.Jpeg);  
  27.                 }  
  28.                 else if (format.Equals(ImageFormat.Png))  
  29.                 {  
  30.                     image.Save(ms, ImageFormat.Png);  
  31.                 }  
  32.                 else if (format.Equals(ImageFormat.Bmp))  
  33.                 {  
  34.                     image.Save(ms, ImageFormat.Bmp);  
  35.                 }  
  36.                 else if (format.Equals(ImageFormat.Gif))  
  37.                 {  
  38.                     image.Save(ms, ImageFormat.Gif);  
  39.                 }  
  40.                 else if (format.Equals(ImageFormat.Icon))  
  41.                 {  
  42.                     image.Save(ms, ImageFormat.Icon);  
  43.                 }  
  44.                 byte[] buffer = new byte[ms.Length];  
  45.                 //Image.Save()会改变MemoryStream的Position,需要重新Seek到Begin  
  46.                 ms.Seek(0, SeekOrigin.Begin);  
  47.                 ms.Read(buffer, 0, buffer.Length);  
  48.                 return buffer;  
  49.             }  
  50.         }  
  51.   
  52.   
  53.         public static Stream ImageToStream(Image image)  
  54.         {  
  55.             ImageFormat format = image.RawFormat;  
  56.             MemoryStream ms = new MemoryStream();  
  57.   
  58.             if (format.Equals(ImageFormat.Jpeg))  
  59.             {  
  60.                 image.Save(ms, ImageFormat.Jpeg);  
  61.             }  
  62.             else if (format.Equals(ImageFormat.Png))  
  63.             {  
  64.                 image.Save(ms, ImageFormat.Png);  
  65.             }  
  66.             else if (format.Equals(ImageFormat.Bmp))  
  67.             {  
  68.                 image.Save(ms, ImageFormat.Bmp);  
  69.             }  
  70.             else if (format.Equals(ImageFormat.Gif))  
  71.             {  
  72.                 image.Save(ms, ImageFormat.Gif);  
  73.             }  
  74.             else if (format.Equals(ImageFormat.Icon))  
  75.             {  
  76.                 image.Save(ms, ImageFormat.Icon);  
  77.             }  
  78.             return ms;  
  79.         }  
  80.   
  81.         //参数是图片的路径    
  82.         public static byte[] GetPictureData(string imagePath)  
  83.         {  
  84.             FileStream fs = new FileStream(imagePath, FileMode.Open);  
  85.             byte[] byteData = new byte[fs.Length];  
  86.             fs.Read(byteData, 0, byteData.Length);  
  87.             fs.Close();  
  88.             return byteData;  
  89.         }  
  90.   
  91.   
  92.   
  93.         /// <summary>  
  94.         /// Convert Byte[] to Image  
  95.         /// </summary>  
  96.         /// <param name="buffer"></param>  
  97.         /// <returns></returns>  
  98.         public static Image BytesToImage(byte[] buffer)  
  99.         {  
  100.             MemoryStream ms = new MemoryStream(buffer);  
  101.             Image image = System.Drawing.Image.FromStream(ms);  
  102.             return image;  
  103.         }  
  104.   
  105.         /// <summary>  
  106.         /// Convert Byte[] to a picture and Store it in file  
  107.         /// </summary>  
  108.         /// <param name="fileName"></param>  
  109.         /// <param name="buffer"></param>  
  110.         /// <returns></returns>  
  111.         public static string CreateImageFromBytes(string fileName, byte[] buffer)  
  112.         {  
  113.             string file = fileName;  
  114.             Image image = BytesToImage(buffer);  
  115.             ImageFormat format = image.RawFormat;  
  116.             if (format.Equals(ImageFormat.Jpeg))  
  117.             {  
  118.                 file += ".jpg";  
  119.             }  
  120.             else if (format.Equals(ImageFormat.Png))  
  121.             {  
  122.                 file += ".png";  
  123.             }  
  124.             else if (format.Equals(ImageFormat.Bmp))  
  125.             {  
  126.                 file += ".bmp";  
  127.             }  
  128.             else if (format.Equals(ImageFormat.Gif))  
  129.             {  
  130.                 file += ".gif";  
  131.             }  
  132.             else if (format.Equals(ImageFormat.Icon))  
  133.             {  
  134.                 file += ".icon";  
  135.             }  
  136.             System.IO.FileInfo info = new System.IO.FileInfo(Path.GetFullPath(@"DownLoadImg\"));   //在当前程序集目录中添加指定目录DownLoadImg  
  137.             System.IO.Directory.CreateDirectory(info.FullName);  
  138.             File.WriteAllBytes(info+file, buffer);   
  139.             return file;  
  140.         }  
  141.     }  
  142. }  

LogHelper.cs代码如下:

 

 

[csharp] view plain copy
 
  1. /// <summary>  
  2.    /// 手动记录错误日志,不用Log4Net组件  
  3.    /// </summary>  
  4.    public class LogHelper  
  5.    {  
  6.        /// <summary>  
  7.        ///  将日志写入指定的文件  
  8.        /// </summary>  
  9.        /// <param name="Path">文件路径,如果没有该文件,刚创建</param>  
  10.        /// <param name="content">日志内容</param>  
  11.        public static void WriteFile(string content)  
  12.        {  
  13.            string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";  
  14.            if (!Directory.Exists(Path))  
  15.            {  
  16.                //若文件目录不存在 则创建  
  17.                Directory.CreateDirectory(Path);  
  18.            }  
  19.            Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";  
  20.            if (!File.Exists(Path))  
  21.            {  
  22.                File.Create(Path).Close();  
  23.            }  
  24.            StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));  
  25.            writer.WriteLine("时间:" + DateTime.Now.ToString());  
  26.            writer.WriteLine("日志信息:" + content);  
  27.            writer.WriteLine("-----------------------------------------------------------");  
  28.            writer.Close();  
  29.            writer.Dispose();  
  30.        }  
  31.   
  32.        /// <summary>  
  33.        ///  将日志写入指定的文件  
  34.        /// </summary>  
  35.        /// <param name="Path">文件路径,如果没有该文件,刚创建</param>  
  36.        /// <param name="content">日志内容</param>  
  37.        public static void WriteFile(int content)  
  38.        {  
  39.            string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";  
  40.            if (!Directory.Exists(Path))  
  41.            {  
  42.                //若文件目录不存在 则创建  
  43.                Directory.CreateDirectory(Path);  
  44.            }  
  45.            Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";  
  46.            if (!File.Exists(Path))  
  47.            {  
  48.                File.Create(Path).Close();  
  49.            }  
  50.            StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));  
  51.            writer.WriteLine("时间:" + DateTime.Now.ToString());  
  52.            writer.WriteLine("日志信息:" + content);  
  53.            writer.WriteLine("-----------------------------------------------------------");  
  54.            writer.Close();  
  55.            writer.Dispose();  
  56.        }  
  57.   
  58.   
  59.        /// <summary>  
  60.        ///  将日志写入指定的文件  
  61.        /// </summary>  
  62.        /// <param name="erroMsg">错误详细信息</param>  
  63.        /// <param name="source">源位置</param>  
  64.        /// <param name="fileName">文件名</param>  
  65.        public static void WriteFile(string erroMsg, string source, string stackTrace, string fileName)  
  66.        {  
  67.            string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";  
  68.            if (!Directory.Exists(Path))  
  69.            {  
  70.                //若文件目录不存在 则创建  
  71.                Directory.CreateDirectory(Path);  
  72.            }  
  73.            Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";  
  74.            if (!File.Exists(Path))  
  75.            {  
  76.                File.Create(Path).Close();  
  77.            }  
  78.            StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));  
  79.            writer.WriteLine("时间:" + DateTime.Now.ToString());  
  80.            writer.WriteLine("文件:" + fileName);  
  81.            writer.WriteLine("源:" + source);  
  82.            writer.WriteLine("错误信息:" + erroMsg);  
  83.            writer.WriteLine("-----------------------------------------------------------");  
  84.            writer.Close();  
  85.            writer.Dispose();  
  86.        }  
  87.    }  

结果如下:

 

技术分享

技术分享

Mongodb数据:

技术分享查找图片:技术分享

使用MongoDB.NET 2.2.4驱动版本对 Mongodb3.3数据库中GridFS增删改查

标签:创建   proc   article   odi   dog   ide   detail   equals   ==   

原文地址:http://www.cnblogs.com/zxtceq/p/7698555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!