服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - MongoDB - MongoDB.NET 2.2.4驱动版本对Mongodb3.3数据库中GridFS增删改查

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

2020-05-09 16:05天风隼 MongoDB

这篇文章主要为大家详细介绍了使用MongoDB.NET 2.2.4驱动版本对Mongodb3.3数据库中GridFS增删改查,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了针对Mongodb3.3数据库中GridFS增删改查,供大家参考,具体内容如下

Program.cs代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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的代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
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的代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
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代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/// <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.NET 2.2.4驱动版本对Mongodb3.3数据库中GridFS增删改查

Mongodb数据:

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

查找图片:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐
  • MongoDB将MongoDB加入到Windows的本地服务项的方法

    将MongoDB加入到Windows的本地服务项的方法

    下面主要针对MongoDB在Windows下加入本地服务项做一些简单的分享。以方便刚接触MongoDB并在Windows环境下进行开发的同学 ...

    MongoDB教程网3012020-04-28
  • MongoDBMongodb数据库误删后的恢复方法(两种)

    Mongodb数据库误删后的恢复方法(两种)

    本文给大家分享两种方法来实现Mongodb数据库误删后的恢复,每种方法给大家介绍的都非常详细,需要的朋友参考下吧 ...

    fyg05249922020-05-18
  • MongoDBMongodb如何开启用户访问控制详解

    Mongodb如何开启用户访问控制详解

    默认启动 MongoDB 服务时没有任何参数,可以对数据库任意操 作,而且可以远程访问数据库,所以推荐开发阶段可以不设置任何参数,但对于生产环境还是要...

    不争5402020-05-10
  • MongoDBMongoDB分片测试

    MongoDB分片测试

    分片是mongoDB扩展的一种方式。分片分割一个collection并将不同的部分存储在不同的机器上,本文给大家介绍MongoDB分片测试,需要的朋友参考下吧 ...

    我思,故我在5532020-05-05
  • MongoDBMongoDB 学习笔记

    MongoDB 学习笔记

    最近在学习MongoDB,小结一下,主要都是一些基础知识,需要的朋友可以参考下 ...

    服务器之家3412020-04-25
  • MongoDBMongoDB简单操作示例【连接、增删改查等】

    MongoDB简单操作示例【连接、增删改查等】

    这篇文章主要介绍了MongoDB简单操作,涉及命令行窗口下使用MongoDB进行简单的连接、增删改查等相关操作技巧,需要的朋友可以参考下 ...

    tinyphp2982020-05-23
  • MongoDBMongo服务重启异常问题的处理方法

    Mongo服务重启异常问题的处理方法

    这篇文章主要给大家介绍了关于Mongo服务重启异常问题的处理方法,这个问题其实还是挺常见的,通过此文学习处理方法,以后遇到了就不会措手不及的,需要的...

    Leafage11842021-08-24
  • MongoDBMongoDB 简单入门教程(安装、基本概念、创建用户)

    MongoDB 简单入门教程(安装、基本概念、创建用户)

    这篇文章主要介绍了MongoDB 简单入门教程(安装、基本概念、创建用户)的相关资料,帮助大家更好的理解和学习使用MongoDB数据库,感兴趣的朋友可以了解下...

    AsiaYe6352021-05-10