C # uses MongoDB to store files

Source: Internet
Author: User
Tags install mongodb

Recently in writing a small thing, need to save some pictures, I used the FTP or direct database to save files, with FTP to save the file feel more trouble, with the database bar, but also to change the field type, modify code, modify query statements, too lazy to change.

Have seen Mongondb's article, with the intention to use Mongon to store files, and then plan to take a look at Baidu, C # operation MongoDB article, are all copying each other, and the age, a lot of things mongodb have no, with the magic on the Internet.

Not in introduction MongoDB is what, how to install, specific Baidu

One: Ready for use 1: Install MongoDB, install Baidu, and download any mongondb visualization software

I MongoDB is installed on the Linux server, the specific installation platform has the reader's own decision

Depending on the software I recommend Robo

2: Create a new Winfrom project

Right-click Project NuGet Package Manager, download

Install the two packages

Second: File Upload

Here, let's do the test with the pictures.

MONGONDB has 2 ways to store, 1: Normal document to store files, maximum for 16mb,2:gridfs storage,

1: Common document Store Sample code

Reference namespaces

using Mongodb.bson; using Mongodb.driver;

Define database name and address word

Private string " mongodb://xx.93.232.xx:27017 "  Privatestring"xxxx"Private Imongodatabase database;

Get database

var New mongoclient (CONNSTR);             if NULL )            {                = client. Getdatabase (dbName);                 New gridfsbucket (database);//This is the initialization of GRIDFS storage            }

Create a Document collection

  Private voidCheckaddcreatecollection (stringCollectionName) {            varCollectionlist =database. Listcollections ().            ToList (); varCollectionnames =Newlist<string>(); //get the names of all collectionsCollectionlist.foreach (x = {Collectionnames.add (x["name"]. asstring);            }); //If you do not have this set, create one (equivalent to creating a table)            if(!collectionnames.contains (CollectionName)) {database.            CreateCollection (CollectionName); }        }

Write a class about the picture information, which is represented by the user's avatar.

 Public class Useravatar         {public  int Get Set ; }          Public byte Get Set ; }    }

If you're wondering why create a class, because any crud operation of Mongon requires a

Imongocollection<tdocument>

Type to operate on. Can be understood as dbset<xxxx> in EF

Get the collection you created earlier

  Private Imongocollection<useravatar> getusercollection (string  name)        {            return Database. Getcollection<useravatar>(name);  The name of the incoming collection        }

Read byte stream of picture

  var bytes = file.readallbytes (@ "C:\Users\ hahaha \desktop\test.jpg");

Inserting a piece of data into the MOGODB

 Private  Asynctask<BOOL> Addavater (useravatar avatar, imongocollection<useravatar>Useravatar) {           awaitUseravatar.insertoneasync (avatar);//Insert a piece of data
The code is judged whether the insert succeeds. varresult = Useravatar.asqueryable (). Where (x = X.avatarid = = Avatar. Avatarid). Select (x =NewUseravatar {Avatar = X.avatar, Avatarid =X.avatarid}). ToList (); if(result.) Count >0) { This. TextBox1.Text = result[0]. Avatarid.tostring (); return true; } return false; }

Let's go inside the robo to see if the insert is successful.

We can see the data.

Fetch a piece of data from Mogodb

 PrivateTask<useravatar> Getuseravatar (intAvatarid,stringCollectionName) {            varTask = Task.run (() =            {                varUseravatar =getusercollection (CollectionName); varresult = Useravatar.asqueryable (). Where (x = X.avatarid = = Avatarid). Select (x =NewUseravatar {Avatar = X.avatar, Avatarid =X.avatarid}).                ToList (); if(result.) Count >0)                {                    returnresult[0]; }                return NULL;            }); returntask; }

Why is the above code not tolist directly behind the where?

A: MongoDB in the document will automatically add a _id field, this time the anti-sequence, it will not be successful, reported exception ID mismatch.

Let's take a look at the effect

Display the code for the picture

Private void ShowImage (byte[] imagebytes)        {            null;             New MemoryStream (imagebytes);             = Image.fromstream (MemoryStream);             New New Size (Picturebox1.width, Picturebox1.height));             = bitMap;        }

Look at the database with the image ID 95 in the not.

2:griffs store files. According to the latest MongoDB documents, basically Baidu to some C # use Gridfs to store files of the article has no use.

GIRDF is used to store files larger than 16m, as described in the Mongon documentation.

Gridfs is a method of storing binary information that is larger than the maximum document size (currently 16MB). when you upload a file to Gridfs, the file is divided into blocks and the individual blocks are uploaded. When you download a file from Gridfs, the original content is re-assembled from the block.

Initialization

Private gridfsbucket buckets;   New Gridfsbucket (database);

according to the official documentation, the Gridfs file is stored in a database using two collections, often referred to as "Fs.files" and "Fs.chunks". each file uploaded to Gridfs has a document in the "Fs.files" collection that contains information about the file and the necessary number of blocks in the Fs.chunks collection to store the contents of the file.

Gridfs "Bucket" is a combination of "fs.files" and "Fs.chunks" collections that collectively represent buckets that can store gridfs files.

GridFSBucketAn object is the root object that represents a Gridfs bucket.

It seems that you can use Girdfsbucket to manage all your files.

Uploading files is very simple.

var id = bucket. Uploadfrombytes ("filename", source); SOURCE byte array varawait bucket. Uploadfrombytesasync ("filename", source);

If the upload is successful, we can see in the robo that the collection group will appear below the

Fs.chunks, and Fs.files two collections

First look at the fs.files, it's stored.

Where Objectid, is the above upload code return value, after the result of ToString,

Download the file by ID to download

   Public  task<byte[]> Downloadfilefromgirdfs (ObjectId id)        {             return  bucket. Downloadasbytesasync (ID);        }

What if I don't know the ID?

You need to find the file first with the filename, upload time Ah can also find

I used the file name to find it. If you want to ask the Objectid can not be found?

Can tell you very clearly, I did not experiment successfully, directly will report abnormal, give me quote unable to determine the serialization information (unable to determine the serialized information)

Find Code

  PublicObjectId Getuploadfileid (stringfileName) {            varFilter = Builders<gridfsfileinfo>. Filter.eq (x =X.filename, Filename); //The eq method is equal to, there are other ways to see the MONGO API documentation specifically            varsort = builders<gridfsfileinfo>. sort.descending (x =x.uploaddatetime); //Press upload time to Flashback            varOptions =Newgridfsfindoptions {Limit=1, Sort=sort}; using(varcursor =buckets. Find (filter,options)) {varFileInfo =cursor. ToList ().                FirstOrDefault (); if(FileInfo! =NULL&& fileinfo.length >0)                {                    returnfileinfo.id; }                return NewObjectId (); }        }

Now let's combine the download and find the code to see the effect

  Private Async void button5_click (object  sender, EventArgs e)        {            var id = Getuploadfileid ("yemobaiavatar");             byte await   Downloadfilefromgirdfs (ID);            ShowImage (imagebytes);        }

Results

Finally, attach the official document address http://mongodb.github.io/mongo-csharp-driver/

C # uses MongoDB to store files

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.