Mongodb.net 2.2.4 Driver version of Mongodb3.3 database Gridfs additions and deletions to check _mongodb

Source: Internet
Author: User
Tags create directory datetime mongoclient mongodb parent directory static class

The example of this article for everyone to share the Mongodb3.3 database for Gridfs additions and deletions, for your reference, the specific contents are as follows

The Program.cs code is as follows:

Internal class Program {private static void Main (string[] args) {Gridfshelper helper = new Gridfshelper ("Mo 
 
   Ngodb://localhost "," Gridfsdemo "," Pictures "); 
   #region upload picture//First//image image = Image.FromFile ("d:\\dog.jpg"); 
   byte[] Imgdata = imagehelper.imagetobytes (image); ObjectId oid = helper. 
 
   Uploadgridfsfrombytes (Imgdata); 
   The second type of//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 Download Pictures//First//objectid Downid = new ObjectId ("578e2d17d22aed1850c7855d"); Byte[] Downdata= Helper. 
   Downloadasbytearray (Downid); 
 
   String Name= imagehelper.createimagefrombytes ("Coolcar", downdata); The second//byte[] Downdata = helper. 
   Downloadasbytesbyname ("QQQ"); String name = Imagehelper.createimageFrombytes ("Dog", downdata); The third kind of//byte[] Downdata = helper. 
   Downloadasbytesbyname ("QQQ"); 
   Image img = imagehelper.bytestoimage (downdata); String path = Path.GetFullPath (@). /.. 
   /downloadimg/") + DateTime.Now.ToString (" yyyymmddhhmmssfff ") +". jpg "; Use path to get the ancestor's parent directory//img for the execution directory of the current application set. 
 
   Save (path, System.Drawing.Imaging.ImageFormat.Jpeg); #endregion #region Find pictures gridfsfileinfo gridfsfileinfo = helper. 
   FindFiles ("man"); 
   Console.WriteLine (gridfsfileinfo.id); #endregion #region Delete the picture//helper. 
   Droppgridfsbucket (); 
  #endregion Console.readkey (); 
 } 
 }

The

GridFSHelper.cs code is as follows:

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*10 
   Readconcern = null, readpreference = NULL, Writeconcern = null}; var bucket = new Gridfsbucket (database, new gridfsbucketoptions {bucketname = "videos", chunksizebytes = 10 
   48576,//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 = Buck Et. 
    Uploadfromstream (filename, source); 
   Return OID; } public byte[] Downloadasbytearray (ObjectId ID) {byte[] bytes = bucket. 
   Downloadasbytes (ID); 
  return bytes; 
   The 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&LT;GRIDFSFILEINFO&GT; 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& gt;. 
   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 would be dropped a, 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<grid Fsfileinfo>. 
   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); 
 } 
  } 
 
 } 
}

The

ImageHelper.cs code is as follows:

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>/////convert image to stream data and save as byte[]/ </summary>///<param name= "image" ></param>///<returns></returns> public Stati C 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 () changes the position of the MemoryStream and requires a new seek to begin Ms. 
    Seek (0, seekorigin.begin); Ms. Read (buffer, 0, buffer.) 
    Length); 
   return buffer; The 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; 
   }//parameter is the path of the picture 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" &GT;&L t;/param>///<returns></returns> public static Image bytestoimage (byte[] buffer) {Memorystre 
   Am 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>///<para M name= "FileName" ></param>///<param name= "buffer" ></param>///<returns></returns&gt 
  ; 
   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\")); Adds the specified directory to the current assembly directory downloadimg System.IO.Directory.CreateDirectory (info. 
   FullName); 
   File.writeallbytes (info+file, buffer); 
  return file; 
 } 
 } 
}

The

LogHelper.cs code is as follows:

<summary>///manually log error logs without log4net components///</summary> public class Loghelper {///<summary>  Writes the log to the specified file///</summary>///<param name= "path" > File path, if there is no such file, just created </param>///<param Name= "Content" > Log content </param> public static void WriteFile (string content) {String Path = Appdomain.cur 
   Rentdomain.basedirectory + "Log"; if (! 
   Directory.Exists (path)) {//If the file directory does not exist then create 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 ("Time:" + DateTime.Now.ToString ()); Writer. 
   WriteLine ("Log information:" + content); Writer. 
   WriteLine ("-----------------------------------------------------------"); Writer. 
   Close (); Writer. 
  Dispose (); ///<summary>///writes the log to the specified file///</summary>///<param name= "path" > File path without the file, just create </param>///<param name= "Content" > Log contents & lt;/param> public static void WriteFile (int content) {string Path = AppDomain.CurrentDomain.BaseDirectory + 
   "Log"; if (! 
   Directory.Exists (path)) {//If the file directory does not exist then create 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 ("Time:" + DateTime.Now.ToString ()); Writer. 
   WriteLine ("Log information:" + content); Writer. 
   WriteLine ("-----------------------------------------------------------"); Writer. 
   Close (); Writer. 
  Dispose (); ///<summary>///writes the log to the specified file///</summary>///<param name= "erromsg" > Error details </param >///<param name= "source" > Source location </param>///<param Name= "filename" > FileName </param> public static void WriteFile (string erromsg, String source, String StackTrace, String 
   FileName) {String Path = AppDomain.CurrentDomain.BaseDirectory + "Log"; if (! 
   Directory.Exists (path)) {//If the file directory does not exist then create 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 ("Time:" + DateTime.Now.ToString ()); Writer. 
   WriteLine ("file:" + filename); Writer. 
   WriteLine ("Origin:" + source); Writer. 
   WriteLine ("error message:" + erromsg); Writer. 
   WriteLine ("-----------------------------------------------------------"); Writer. 
   Close (); Writer. 
  Dispose (); 
 } 
 }

The results are as follows:

MongoDB Data:

Find a Picture:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.