当前位置: 移动技术网 > IT编程>数据库>MongoDB > MongoDB.NET 2.2.4驱动版本对Mongodb3.3数据库中GridFS增删改查

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

2017年12月08日  | 移动技术网IT编程  | 我要评论

中国塑胶原料网,杨澍,慧明网

本文实例为大家分享了针对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数据:

查找图片:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网