Ehsan Ghanbari

Experience, DotNet, Solutions

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

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);

        }

 



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
What's the DDD-lite?
Multiple submit buttons in asp.net MVC