使用MongoDB.NET 2.2.4驱动版本对 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数据:
查找图片:
使用MongoDB.NET 2.2.4驱动版本对 Mongodb3.3数据库中GridFS增删改查的更多相关文章
- 十四:SpringBoot-配置MongoDB数据库,实现增删改查逻辑
SpringBoot-配置MongoDB数据库,实现增删改查逻辑 1.MongoDB数据库 1.1 MongoDB简介 1.2 MongoDB特点 2.SpringBoot整合MongoDB 2.1 ...
- MongoDB 基础命令——数据库表的增删改查——遍历操作表中的记录
分组排序查询最大记录 //对 "catagory" 不等于 null 的数据进行分组查询,且查询结果倒序 db.getCollection('userAccount').aggre ...
- SpringBoot2.0 基础案例(15):配置MongoDB数据库,实现增删改查逻辑
本文源码:GitHub·点这里 || GitEE·点这里 一.NoSQL简介 1.NoSQL 概念 NoSQL( Not Only SQL ),意即"不仅仅是SQL".对不同于传统 ...
- MongoDB增删改查表文档
MongoDB 是一个基于分布式文件存储的数据库.由 C++ 语言编写,是一个基于分布式文件存储的开源数据库系统.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关 ...
- Mongodb c#增删改查
写在前面 最近项目需要,就研究了下mongodb,也是为了快速上手,就自己弄了一个简单的例子,这里记录一下. Mongodb 传统的关系数据库一般由数据库(database).表(table).记录( ...
- nodejs笔记五--MongoDB基本环境配置及增删改查;
一.基本环境配置: 1,首先到官网(http://www.mongodb.org/downloads )下载合适的安装包,然后一步一步next安装,当然可以自己更改安装目录:安装完成之后,配置环境变量 ...
- 大数据之路week05--day01(JDBC 初识之实现一个系统 实现用户选择增删改查 未优化版本)
要求,实现用户选择增删改查. 给出mysql文件,朋友们可以自己运行导入到自己的数据库中: /* Navicat MySQL Data Transfer Source Server : mysql S ...
- MongoDB学习-->命令行增删改查&JAVA驱动操作Mongodb
MongoDB 是一个基于分布式文件存储的数据库. 由 C++ 语言编写.旨在为 WEB 应用提供可扩展的高性能数据存储解决方案. MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关 ...
- mongoDB 学习笔记纯干货(mongoose、增删改查、聚合、索引、连接、备份与恢复、监控等等)
最后更新时间:2017-07-13 11:10:49 原始文章链接:http://www.lovebxm.com/2017/07/13/mongodb_primer/ MongoDB - 简介 官网: ...
随机推荐
- Android动画系列 - PropertyAnim 详解
前言:上一篇文章传统View动画与Property动画基础及比较简单对Android动画系统的基础做了介绍,本篇文章将对PropertyAnimation进行全面深入的探讨,本篇文章可以分为两大块,从 ...
- 使用Pig对手机上网日志进行分析
在安装成功Pig的基础上.本文将使用Pig对手机上网日志进行分析,详细过程例如以下: 写在前面: 手机上网日志文件phone_log.txt.文件内容 及 字段说明部分截图例如以下 需求分析 显示每一 ...
- Django-mysq数据库链接问题
Django链接MySQL数据库有可能会报no model named MySQLdb, 解决办法: 首先安装pymysql 然后进入到项目目录,找到__init__.py文件,在里面添加 impor ...
- C++ "#"的作用和使用方法
本系列文章由 @yhl_leo 出品,转载请注明出处. 文章链接: http://blog.csdn.net/yhl_leo/article/details/48879093 1 #和##的作用和使用 ...
- npm 淘宝设置代理
直接安装cnpm导致无限索引,因此直接使用代理 方法一: 直接在当前用户文件夹下,npmrc 文件上直接设置代理:registry=https://registry.npm.taobao.org 方法 ...
- js event 的target 和currentTarget
target 点击的实际tag currentTarget 绑定事件的target
- 启动app-inspector报Internal Server Error
前言 应用工具app-inspector可以协助定位IOS版App的控件元素,然鹅启动时报Internal Server Error! 解决办法 一.找到XCTestWD项目 目录: /usr/loc ...
- 使用Entity Framework和WCF Ria Services开发SilverLight之6:查找指定字段
对数据库表指定字段的查找,又是实际工作中的一项必要工作.SL客户端仅获取实际需要的指定的字段,好处很多,比如:有助于减少网络流量. 有两类这样的使用场景. 1:联表查询不需要外键表 在上一篇中,我们使 ...
- Erlang Shell调试网络程序真方便
Erlang的shell功能强大,这里我将它当成我的客户端.可以动态的输入你需要发送的内容,也可以动态的接收内容,就像调试器一样,在开发过程中起到很重要的作用.具体使用方式如下: C:\Documen ...
- Redis(二)延迟队列
1.目录 延迟队列 进一步优化 2.延迟队列 package com.redis; import java.lang.reflect.Type; import java.util.Set; impor ...