Blog

Filter posts by Category Or Tag of the Blog section!

How to upload and download file in MongoDB with C# driver

Wednesday, 04 May 2016

MongoDB offers the GridFS driver for handling files and you can easily upload files into MongoDB. There are lots of benefit of Storing files and metadata in one place in DB. The first thing which comes into mind is the replication. You can easily replicate the database in document store databases. For uploading and downloading a file you should use FridFS like below:

 

 

    public ObjectId UploadFile(GridFSBucket bucket, string path, string file)

        {

           //path: for example (@"c:\C\me.png"))

            using (var readFile = File.OpenRead(path)

            {

                var task = Task.Run<ObjectId>(() => { return

                    bucket.UploadFromStreamAsync(file, readFile);

                });


                return task.Result;

            }

        }
 

 

    public void DownloadFile(GridFSBucket bucket, ObjectId id, string file)

        {

            var bytefile = bucket.DownloadAsBytesByNameAsync(file);

            Task.WaitAll(bytefile);

            var bytes = bytefile.Result;

            var final = bucket.DownloadAsBytesAsync(id);

            Task.WaitAll(final);

        }

 

 simply you can use the above methods in a console application:

 

static void Main(string[] args)

        {

            var client = new MongoClient("mongodb://localhost");

            var database = client.GetDatabase("MyDatabase");

            var bucket = new GridFSBucket(database);

            var fileId = UploadFile(bucket);

            DownloadFile(bucket, fileId);

        }

 

Category: Software

Tags: MongoDB

comments powered by Disqus