Program.cs代码如下:

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

GridFSHelper.cs的代码如下:

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

ImageHelper.cs的代码如下:

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

LogHelper.cs代码如下:

  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. /// <summary>
  32. ///  将日志写入指定的文件
  33. /// </summary>
  34. /// <param name="Path">文件路径,如果没有该文件,刚创建</param>
  35. /// <param name="content">日志内容</param>
  36. public static void WriteFile(int content)
  37. {
  38. string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";
  39. if (!Directory.Exists(Path))
  40. {
  41. //若文件目录不存在 则创建
  42. Directory.CreateDirectory(Path);
  43. }
  44. Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";
  45. if (!File.Exists(Path))
  46. {
  47. File.Create(Path).Close();
  48. }
  49. StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));
  50. writer.WriteLine("时间:" + DateTime.Now.ToString());
  51. writer.WriteLine("日志信息:" + content);
  52. writer.WriteLine("-----------------------------------------------------------");
  53. writer.Close();
  54. writer.Dispose();
  55. }
  56. /// <summary>
  57. ///  将日志写入指定的文件
  58. /// </summary>
  59. /// <param name="erroMsg">错误详细信息</param>
  60. /// <param name="source">源位置</param>
  61. /// <param name="fileName">文件名</param>
  62. public static void WriteFile(string erroMsg, string source, string stackTrace, string fileName)
  63. {
  64. string Path = AppDomain.CurrentDomain.BaseDirectory + "Log";
  65. if (!Directory.Exists(Path))
  66. {
  67. //若文件目录不存在 则创建
  68. Directory.CreateDirectory(Path);
  69. }
  70. Path += "\\" + DateTime.Now.ToString("yyMMdd") + ".log";
  71. if (!File.Exists(Path))
  72. {
  73. File.Create(Path).Close();
  74. }
  75. StreamWriter writer = new StreamWriter(Path, true, Encoding.GetEncoding("gb2312"));
  76. writer.WriteLine("时间:" + DateTime.Now.ToString());
  77. writer.WriteLine("文件:" + fileName);
  78. writer.WriteLine("源:" + source);
  79. writer.WriteLine("错误信息:" + erroMsg);
  80. writer.WriteLine("-----------------------------------------------------------");
  81. writer.Close();
  82. writer.Dispose();
  83. }
  84. }

结果如下:

Mongodb数据:

查找图片:

使用MongoDB.NET 2.2.4驱动版本对 Mongodb3.3数据库中GridFS增删改查的更多相关文章

  1. 十四:SpringBoot-配置MongoDB数据库,实现增删改查逻辑

    SpringBoot-配置MongoDB数据库,实现增删改查逻辑 1.MongoDB数据库 1.1 MongoDB简介 1.2 MongoDB特点 2.SpringBoot整合MongoDB 2.1 ...

  2. MongoDB 基础命令——数据库表的增删改查——遍历操作表中的记录

    分组排序查询最大记录 //对 "catagory" 不等于 null 的数据进行分组查询,且查询结果倒序 db.getCollection('userAccount').aggre ...

  3. SpringBoot2.0 基础案例(15):配置MongoDB数据库,实现增删改查逻辑

    本文源码:GitHub·点这里 || GitEE·点这里 一.NoSQL简介 1.NoSQL 概念 NoSQL( Not Only SQL ),意即"不仅仅是SQL".对不同于传统 ...

  4. MongoDB增删改查表文档

    MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写,是一个基于分布式文件存储的开源数据库系统.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关 ...

  5. Mongodb c#增删改查

    写在前面 最近项目需要,就研究了下mongodb,也是为了快速上手,就自己弄了一个简单的例子,这里记录一下. Mongodb 传统的关系数据库一般由数据库(database).表(table).记录( ...

  6. nodejs笔记五--MongoDB基本环境配置及增删改查;

    一.基本环境配置: 1,首先到官网(http://www.mongodb.org/downloads )下载合适的安装包,然后一步一步next安装,当然可以自己更改安装目录:安装完成之后,配置环境变量 ...

  7. 大数据之路week05--day01(JDBC 初识之实现一个系统 实现用户选择增删改查 未优化版本)

    要求,实现用户选择增删改查. 给出mysql文件,朋友们可以自己运行导入到自己的数据库中: /* Navicat MySQL Data Transfer Source Server : mysql S ...

  8. MongoDB学习-->命令行增删改查&JAVA驱动操作Mongodb

    MongoDB 是一个基于分布式文件存储的数据库. 由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关 ...

  9. mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)

    最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...

随机推荐

  1. Android动画系列 - PropertyAnim 详解

    前言:上一篇文章传统View动画与Property动画基础及比较简单对Android动画系统的基础做了介绍,本篇文章将对PropertyAnimation进行全面深入的探讨,本篇文章可以分为两大块,从 ...

  2. 使用Pig对手机上网日志进行分析

    在安装成功Pig的基础上.本文将使用Pig对手机上网日志进行分析,详细过程例如以下: 写在前面: 手机上网日志文件phone_log.txt.文件内容 及 字段说明部分截图例如以下 需求分析 显示每一 ...

  3. Django-mysq数据库链接问题

    Django链接MySQL数据库有可能会报no model named MySQLdb, 解决办法: 首先安装pymysql 然后进入到项目目录,找到__init__.py文件,在里面添加 impor ...

  4. C++ &quot;#&quot;的作用和使用方法

    本系列文章由 @yhl_leo 出品,转载请注明出处. 文章链接: http://blog.csdn.net/yhl_leo/article/details/48879093 1 #和##的作用和使用 ...

  5. npm 淘宝设置代理

    直接安装cnpm导致无限索引,因此直接使用代理 方法一: 直接在当前用户文件夹下,npmrc 文件上直接设置代理:registry=https://registry.npm.taobao.org 方法 ...

  6. js event 的target 和currentTarget

    target  点击的实际tag currentTarget 绑定事件的target

  7. 启动app-inspector报Internal Server Error

    前言 应用工具app-inspector可以协助定位IOS版App的控件元素,然鹅启动时报Internal Server Error! 解决办法 一.找到XCTestWD项目 目录: /usr/loc ...

  8. 使用Entity Framework和WCF Ria Services开发SilverLight之6:查找指定字段

    对数据库表指定字段的查找,又是实际工作中的一项必要工作.SL客户端仅获取实际需要的指定的字段,好处很多,比如:有助于减少网络流量. 有两类这样的使用场景. 1:联表查询不需要外键表 在上一篇中,我们使 ...

  9. Erlang Shell调试网络程序真方便

    Erlang的shell功能强大,这里我将它当成我的客户端.可以动态的输入你需要发送的内容,也可以动态的接收内容,就像调试器一样,在开发过程中起到很重要的作用.具体使用方式如下: C:\Documen ...

  10. Redis(二)延迟队列

    1.目录 延迟队列 进一步优化 2.延迟队列 package com.redis; import java.lang.reflect.Type; import java.util.Set; impor ...