关闭

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

标签: gridfsc#mongodb增删改查.NET
36982人阅读 评论(2) 收藏 举报
分类:

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数据:

查找图片:

1
0
查看评论

C#如何向MongoDB GridFs中存储文件

来自:http://outofmemory.cn/code-snippet/1745/C-how-MongoDB-GridFs-storage-file  如下示例代码,使用的是MongoDB官方的csharp 驱动程序: var server = MongoServer.Creat...
  • ArvinStudy
  • ArvinStudy
  • 2013-02-04 16:50
  • 1647

MongoDB——GridFS使用

MongoDB提供了一个命令行工具mongofiles可以来处理GridFS 使用命令如下: 将文件上传到monggodb :mongofiles put xxx.txt从mongodb中获得已经存储的文件:mongofiles get xxx...
  • Shiyaru1314
  • Shiyaru1314
  • 2016-09-27 17:49
  • 263

MongoDB GridFS最佳应用概述

《MongoDB GridFS的最佳应用概述》作者:chszs,转载需注明。博客主页:http://blog.csdn.net/chszsGridFS是MongoDB数据库之上的一个简单文件系统抽象。如果你熟悉Amazon S3的话,那么GridFS与之相似。为什么像MongoDB这样的NoSQL数...
  • chszs
  • chszs
  • 2014-02-28 10:21
  • 15087

GridFS详细分析

GridFS简介 GridFS是MongoDB中的一个内置功能,可以用于存放大量小文件。 http://www.mongodb.org/display/DOCS/GridFS http://www.mongodb.org/display/DOCS/GridFS+Specification G...
  • hengyunabc
  • hengyunabc
  • 2012-02-25 19:21
  • 30144

MongoDB GridFS 数据读取效率 benchmark

GridFS 是 MongoDB 下的一个子模块,利用这一模块,可以实现使用MongoDB存储文件,MongoDB 二进制包的bin目录下的mongofile 命令即可模拟实现该功能。 原文链接:http://lgone.com/html/y2010/815.html 数据来源: http:/...
  • joeyon
  • joeyon
  • 2015-05-15 15:08
  • 472

NoSql-MongoDB GridFS+ASP.NET MVC实现上传,显示

之前一篇文章介绍了如何在dos窗口下对MongoDB进行一些简单的操作,但是不管学习什么,最终还是要应用于自己的项目当中,本篇主要介绍在MVC框架中如何应用于我们的MongoDB。 GridFS介绍: GridFS是MongoDb中的一个内置功能,可以用于存放大量小文件。我们可以使用MongoVUE...
  • huo065000
  • huo065000
  • 2015-09-14 18:07
  • 1738

c#.net连接mongodb入门(一)

.net 连接 mongodb
  • fhl812432059
  • fhl812432059
  • 2016-06-01 15:43
  • 3918

ASP.NET MVC与MongoDB的整体搭建

Mongo+ASP.NET MVC
  • github_37287822
  • github_37287822
  • 2017-07-02 21:11
  • 606

.net mongodb

第一节 MongoDB介绍及下载与安装 引言    MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。他支持的数据结构非常松散,是类似json的bjson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点...
  • hliq5399
  • hliq5399
  • 2012-04-27 10:53
  • 9705

asp.net 使用 MongoDB 初体验

首先:驱动 如果asp.net 想使用MongoDB,.net没有自带的链接类。得用第三方或官方的链接类。 当然有很多种驱动,我就不一一介绍了。 今天我就介绍一个我比较常用的驱动-----MongoDB。 接下来,我们还要去下载MongoDB的C#驱动,它可以让我们在C#...
  • u011047160
  • u011047160
  • 2016-07-28 18:06
  • 942
    个人资料
    • 访问:1297166次
    • 积分:18616
    • 等级:
    • 排名:第593名
    • 原创:312篇
    • 转载:932篇
    • 译文:123篇
    • 评论:297条
    博客专栏
    文章分类
    打赏
    如果你觉得我的文章对您有用,请随意打赏。 微信 支付宝